Categories
JavaScript Answers

How to remove all multiple spaces in JavaScript and replace with single space?

Spread the love

Sometimes, we want to remove all multiple spaces in JavaScript and replace with single space.

In this article, we’ll look at how to remove all multiple spaces in JavaScript and replace with single space.

How to remove all multiple spaces in JavaScript and replace with single space?

To remove all multiple spaces in JavaScript and replace with single space, we use the string replace method with a regex.

For instance, we write

str = str.replace(/ +(?= )/g, "");

to call str.replace with the / +(?= )/g regex to match all instances of multiple spaces in the str string.

We use +(?= ) to match multiple spaces.

And we use the g flag to find all matches.

Then we replace them all with empty strings.

Conclusion

To remove all multiple spaces in JavaScript and replace with single space, we 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 *