Thu Oct 07 2021·1 min read
Photo by Jamie Street
To replace multiple spaces with a single space, call the
with a regex that matches all space characters, followed by 1 or more spaces.
replace method returns a new string with the matched characters
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.
I'll send you 1 email a week with links to all of the articles I've written that week