javascript

Replace multiple spaces between words with single space using javascript

To remove multiple spaces that exist between string words and replace them with a single space, we can use regular expressions.

//Remove spaces along with tab spaces, new lines
const input_str = "Have   you   seen    spaces   here.";
const result_str = input_str.replace(/\s\s+/g, ' ');
console.log(result_str);
// -> Have you seen spaces here.

Here, we have a string variable named input_str that contains words with more than one space between them. We want to remove those spaces with a single space between each word. We are using regex code for that and it will replace all the spaces, new lines, and tabs with a single space.

If you do not want your code to replace tabs or new lines with space, you can use the below code.

const input_str = "This   string   contains multiple     spaces";
const result_str = string = input_str.replace(/  +/g, ' ');

console.log(result_str);
// -> This string contains multiple spaces
The code here will ignore tabs and new lines and will only replace more than one space with a single space.
const input = "   Success   is   a journey    not   a   destination   ";

result = input.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
console.log(result);
// -> Success is a journey not a destination
If you have spaces at the beginning and at the end of the string then you can use the above code. It will remove trailing spaces and replace multiple spaces between words.
Was this helpful?