Borislav Hadzhiev
Last updated: Oct 7, 2021
Check out my new book
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.
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.
replace
method does not change the original string instead it returns a new string with the matched characters replaced. Strings are immutable in JavaScript.