1

What is the regex to check if a string is not all spaces (spaces = spacebar, tab etc.)? It's ok if there is at least one or more non space characters in string.

Example:

str = ''       // not allowed
str = '      ' // not allowed
str = '     d' // allowed
str = 'a    '  // allowed
str = '  d  '  // allowed
str = '  @s '  // allowed

I was trying this, but this seems to return true for everything...

str = '   a';
regex = /[\s]+/g;;
console.log(regex.test(str));

P.S I cannot use trim in here.

2 Answers 2

4

All you need is a test for \S, a non-space character:

const isAllowed = str => /\S/.test(str);

console.log(
  isAllowed(''),
  isAllowed('    '),
  isAllowed('    d'),
  isAllowed('a    '),
);

Sign up to request clarification or add additional context in comments.

Comments

0

We could also use trim() here. A string containing only whitespace would have a trimmed length of zero:

var input = "   \t\t\t  \n";
if (input.trim().length == 0) {
    console.log("input has only whitespace");
}

input = "  Hello World!  \t\n ";
if (input.trim().length == 0) {
    console.log("input has only whitespace");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.