Reputation: 6365
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.
Upvotes: 1
Views: 378
Reputation: 521093
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");
}
Upvotes: 0
Reputation: 370699
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 '),
);
Upvotes: 4