Sometimes, we want to detect if a JavaScript string contains any spaces.
In this article, we’ll look at how to detect if a JavaScript string contains any spaces.
Detect if a JavaScript String Contains Any Spaces
To detect if a JavaScript string contains any spaces, we can use the JavaScript regex test method.
For instance, we can write:
const str = 'foo bar'
console.log(/\s/.test(str))
We call .test on the /\s/ regex to check if str has any spaces.
Since str has a space, the console log should log true .
Conclusion
To detect if a JavaScript string contains any spaces, we can use the JavaScript regex test method.
 
		
2 replies on “How to Detect if a JavaScript String Contains Any Spaces?”
You have missed a backslash there. It should be
console.log(/\s/.test(str))
Thanks. I fixed it.