Search code snippets, questions, articles...

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, ' ');
// -> 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.

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, ' ');

// -> 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, "");
// -> 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?
Programming Feeds
Learn something new everyday on Devsheet