Jump to content
Larry Ullman's Book Forums

Check If A String Contains No Spaces


Recommended Posts

Quote [page 413 - Character Classes... ]:

 

 

3. Check if a string contains no spaces. The \S character class shortcut will match non-white space characters. To make sure that the entire string contains no spaces, use the caret and the dollar sign: ^\S$. If you don’t use those, then all the pattern is confirming is that the subject contains at least one non-space character.

 

But, ^\S$ does not check if a string contains no spaces, it only checks if a string is a non-white space character, right?

 

2rrw41z.jpg

Link to comment
Share on other sites

Yes, that is correct.

 

One thing the quote above does not clarify is whether we are talking about a "space" or any whitespace character. \s refers to any whitespace character, not just a space.

 

A better way to check if a string contains one or more spaces is:

str.indexOf(' ') !== -1;

That's the most efficient way. You can also use the following regex if you want, although it's not necessary in this case:

/ /.test(str);

You can also modify the regex above to check for any whitespace characters:

/\s/.test(str);

That answer your concerns?

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...