Categories
JavaScript Answers

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 can call the string replace method.

For instance, we write

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

to call replace with /\s/g and '' to replace all whitespaces with empty strings.

We use \s to match whitespaces.

g makes replace do the replacement on all matches.

Conclusion

To remove whitespaces inside a string in JavaScript, we can call the string 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. Required fields are marked *