Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  127] [ 6]  / answers: 1 / hits: 146254  / 11 Years ago, fri, july 12, 2013, 12:00:00

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);
}

More From » regex

 Answers
86

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: [ fnrtv​u00a0u1680​u180eu2000​u2001u2002​u2003u2004​u2005u2006​u2007u2008​u2009u200a​u2028u2029​​u202fu205f​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.)


[#77035] Thursday, July 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycie

Total Points: 414
Total Questions: 96
Total Answers: 117

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;