Replace Multiple Spaces with a Single Space in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 min read

banner

Photo by Jamie Street

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee