Replace Multiple Spaces with a Single Space in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 7, 2021

banner

Check out my new book

Replace Multiple Spaces with a Single Space #

To replace multiple spaces with a single space, call the replace() method with a regex that matches all space characters, followed by 1 or more spaces. The replace method returns a new string with the matched characters replaced.

index.js
const str = 'A very spaced string'; const singleSpaces = str.replace(/ +/g, ' '); console.log(singleSpaces); // 👉️ "A very spaced string"

The first parameter we passed to the String.replace method is a regular expression that matches a space, followed by 1 or more spaces.

Notice that there are 2 spaces the in regex. With the + symbol we specify that we want to match 1 or more space characters.

We use the g (global) flag to indicate that we want to match all occurrences, not just the first one.

The second parameter is the replacement for each match. In our case we replace multiple spaces with a single space.

The replace method does not change the original string instead it returns a new string with the matched characters replaced. Strings are immutable in JavaScript.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.