To replace multiple spaces with a single space in JavaScript, use the replace() method with a regex that matches all two or more consecutive whitespace characters.

The replace() method returns a new string with the matched values replaced without changing the original string.

const str = 'Lean    how  to   code  in   JavaScript.'

const updatedStr = str.replace(/  +/g, ' ')

console.log(updatedStr)
// Lean how to code in JavaScript.

The replace() method accepts a value or a regular expression to search for in the string.

If you pass a value, only the first instance will be replaced. To replace all occurrences of a value, use a regular expression with the g modifier set.

The replace() method replaces all values that match the given regular expression with the new value and returns the new string.

Alternatively, you could use the replaceAll() method to multiple spaces with a single space:

const str = 'Lean    how  to   code  in   JavaScript.'

const updatedStr = str.replaceAll(/  +/g, ' ')

console.log(updatedStr)
// Lean how to code in JavaScript.

The replaceAll() method was introduced in ES2021. It replaces all occurrences of the search string with the replacement text and returns a new string.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.