# How to replace multiple spaces with a single space in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 16, 2022, updated Oct 23, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-replace-multiple-spaces-with-single-space

> Learn how to use the replace() method with a regex to replace multiple spaces with a single space in JavaScript.

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.

```javascript
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](https://attacomsian.com/blog/javascript-regular-expressions) 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: 

```javascript
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.
