Categories
JavaScript Answers

How to remove spaces with JavaScript regular expression?

Spread the love

Sometimes, we want to remove spaces with JavaScript regular expression.

In this article, we’ll look at how to remove spaces with JavaScript regular expression.

How to remove spaces with JavaScript regular expression?

To remove spaces with JavaScript regular expression, we can use the string replace method.

For instance, we write

const str = "foo is bar".replace(/ /g, "");

to call "foo is bar".replace with the / /g regex to match all spaces and replace them all with empty strings.

The g flag will make replace replace all matches of the regex.

Conclusion

To remove spaces with JavaScript regular expression, we can use 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 *