Categories
JavaScript Answers

How to detect string which contains only spaces with JavaScript?

Spread the love

Sometimes, we want to detect string which contains only spaces with JavaScript.

In this article, we’ll look at how to detect string which contains only spaces with JavaScript.

How to detect string which contains only spaces with JavaScript?

To detect string which contains only spaces with JavaScript, we can use the string trim method.

For instance, we write

if (!str.trim()) {
  //...
}

to check if the string returned by str.trim is an empty string.

If it is, then the str string has only whitespaces in it.

Conclusion

To detect string which contains only spaces with JavaScript, we can use the string trim method.

By John Au-Yeung

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

Leave a Reply

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