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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Detect if a JavaScript String Contains Any Spaces?”

Leave a Reply

Your email address will not be published. Required fields are marked *