6

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!

4 Answers 4

14

You 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)

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

4 Comments

Thanks Gabi, this is the right way. But so I test all words with al most one space, and I wanted to filter the strings with only spaces
rob, you were too quick and I didn't see you comment. Your suggestion is the right for me - it works fine. Thank you all, guys!
you people are too fast. i never get to answer a question I actually know :P
NOTE: This does not account for multiline strings
0

Just use the space character instead of the \s.

'   '.match(/ +/)
''.match(/ +/)

Output

["   ", index: 0, input: "   ", groups: undefined]'
null

Comments

0

You could do this same check with !word.trim() as well, and ignore regex completely.

Comments

-2

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';
   }

4 Comments

That code is subtly different from OP's: Yours allows the empty string; OP's and the other answer don't. Also, console & ... makes no sense and the parens around word are redundant.
I don't think so, he want's to find fields composed of only spaces, so I wrote a check to find it. What you do with the result inside the statement or if you want to switch the statement to !==, and if you write it to console even only for testing or development - does this really matter? And sure, the parens are redundant, but also this doesn't harm the solution itself in any way, isn't it?
But, you are using regex!
OK, that's right, the text is wrong, I will change that, THX!

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.