Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if string contains any spaces

How do I detect if a string has any whitespace characters?

The below only detects actual space characters. I need to check for any kind of whitespace.

if(str.indexOf(' ') >= 0){     console.log("contains spaces"); } 
like image 945
Malcr001 Avatar asked Jul 12 '13 13:07

Malcr001


People also ask

How do you check if a string has any spaces?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.

How do you check if a string contains a space C ++?

C++ isspace() The isspace() function in C++ checks if the given character is a whitespace character or not.

How do you check if a character in a string is a space in Java?

The isWhitespace(char ch) method returns a Boolean value, i.e., true if the given(or specified) character is a Java white space character. Otherwise, this method returns false.

How do you check if string is empty with spaces?

1. String isBlank() Method. This method returns true if the given string is empty or contains only white space code points, otherwise false .


1 Answers

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {     // It has any kind of whitespace } 

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {     // It has only spaces, or is empty } 

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {     // It has only whitespace } 

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

like image 68
T.J. Crowder Avatar answered Sep 22 '22 06:09

T.J. Crowder