Detect if string contains any spaces
javascript, regex
Solution
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.)
Problem
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"); } ```