Replace Multiple Spaces with Single Space in JavaScript

Javascript replace multiple spaces with single space Example; In this tutorial you will learn How to Replace Multiple (2 or more) Spaces with Single Space ini Javascript;

In Js you can simply use the JavaScript replace() to replace the multiple spaces inside a string.

const str = 'This   is   very    spaced   string';

const singleSpaces = str.replace(/  +/g, ' ');
console.log(singleSpaces); // "This is very spaced string"

If you also want to cover tabs, newlines, etc, just replace \s\s+ with ‘ ‘:

const str = 'This   is   very    spaced   string';

const singleSpaces = str.replace(/\s\s+/g, ' ');

console.log(singleSpaces); // "This is very spaced string"

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.