Sometimes, we want to check if a string has white space with JavaScript.
In this article, we’ll look at how to check if a string has white space with JavaScript.
How to check if a string has white space with JavaScript?
To check if a string has white space with JavaScript, we can use the regex test method.
For instance, we write
const hasWhiteSpace = (s) => {
return /s/g.test(s);
};
to define the hasWhiteSpace function that checks if string s has any whitespaces with /s/g.test.
We use s to match any whitespaces in s.
The g flag makes test check for all instances of whitespaces.
Conclusion
To check if a string has white space with JavaScript, we can use the regex test method.