How to remove whitespaces inside a string in JavaScript?

Spread the love

Sometimes, we want to remove whitespaces inside a string in JavaScript.

In this article, we’ll look at how to remove whitespaces inside a string in JavaScript.

How to remove whitespaces inside a string in JavaScript?

To remove whitespaces inside a string in JavaScript, we call the string replace method.

For instance, we write

const str = "hello world".replace(/\s/g, "");

to call replace with /\s/g and '' to replace allk whitespaces in "hello world" with empty strings and return the new string.

\s matches all whitespaces.

g makes replace replace all matches.

Conclusion

To remove whitespaces inside a string in JavaScript, we call the string replace method.

Leave a Reply

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