Categories
JavaScript Answers

How to replace all whitespace characters with JavaScript?

Spread the love

Sometimes, we want to replace all whitespace characters with JavaScript.

In this article, we’ll look at how to replace all whitespace characters with JavaScript.

How to replace all whitespace characters with JavaScript?

To replace all whitespace characters with JavaScript, we can use the string replace method with a regex.

For instance, we write

str = str.replace(/\s/g, "X");

to call str.replace with /\s/g to match all whitespace characters.

\s matches all whitespace characters.

The g flag make replace get all matches.

And we replace them all with 'X'.

Conclusion

To replace all whitespace characters with JavaScript, we can use the string replace method with a regex.

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 *