Search code snippets, questions, articles... Chrome Extension

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.
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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.

Search Index Data (The code snippet can also be found with below search text)

Replace multiple space with single space javascript
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?
0 Comments
Join Devsheet Ask a Question