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"); }
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.
C++ isspace() The isspace() function in C++ checks if the given character is a whitespace character or not.
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.
1. String isBlank() Method. This method returns true if the given string is empty or contains only white space code points, otherwise false .
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With