I need to filter a field composed of only spaces; something like:
if (word == /((\s)+)/ ) return 'no name'
but it doesn't work ... any other ideas? thank you for your ideas!
I need to filter a field composed of only spaces; something like:
if (word == /((\s)+)/ ) return 'no name'
but it doesn't work ... any other ideas? thank you for your ideas!
Share Improve this question edited Aug 16, 2016 at 14:01 Dylan Meeus 5,8023 gold badges32 silver badges49 bronze badges asked Jun 24, 2011 at 17:46 MarcoMarco 611 gold badge1 silver badge2 bronze badges4 Answers
Reset to default 14You should use if(/^\s+$/.test(word))
. (Notice the ^
and $
, without them the regex will hold for any string that has at least a space-like character)
Just use the space
character instead of the \s
.
' '.match(/ +/)
''.match(/ +/)
Output
[" ", index: 0, input: " ", groups: undefined]'
null
You could do this same check with !word.trim()
as well, and ignore regex completely.
How about NOT checking "word" by RegExp but using RegExp to replace all whitespaces and look what's left. If it's empty "word" is only composed by whitespaces:
if (word.replace(/\s+/, "") === "") {
console && console.log("empty string found!");
return 'no name';
}