Categories
JavaScript Answers

How to check if a text is all white space characters in JavaScript?

Spread the love

Sometimes, we want to check if a text is all white space characters in JavaScript.

In this article, we’ll look at how to check if a text is all white space characters in JavaScript.

How to check if a text is all white space characters in JavaScript?

To check if a text is all white space characters in JavaScript, we use the replace method.

For instance, we write

const trimmedUserText = userText.replace(/^\s+/, "").replace(/\s+$/, "");
if (trimmedUserText === "") {
  // ...
} else {
  // ...
}

to call replace to replace all whitespaces at the start of the string with empty strings with

userText.replace(/^\s+/, "")

Then we call replace again with /\s+$/ and '' to replace the rest of the whitespaces with empty strings.

And then a new string is returned with the replacements.

If trimmedUserText is an empty string, that means userText is all whitespace.

Conclusion

To check if a text is all white space characters in JavaScript, we use the replace 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.