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);
}
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);
}
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: [ fnrtvu00a0u1680u180eu2000u2001u2002u2003u2004u2005u2006u2007u2008u2009u200au2028u2029u202fu205fu3000]
.
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.)