Categories
JavaScript Answers

How to Detect if a JavaScript String Contains Any Spaces?

Spread the love

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?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.