In javascript / regex, how do you remove double spaces inside a string?

If I have a line with several spaces between words:

Be an excellent person 

using javascript / regex how to remove extraneous internal spaces so that it becomes:

 Be an excellent person 
+13
source share
4 answers

You can use the regular expression /\s{2,}/g :

 var s = "Be an excellent person" s.replace(/\s{2,}/g, ' '); 
+19
source

This regex should fix the problem:

 var t = 'Be an excellent person'; t.replace(/ {2,}/g, ' '); // Output: "Be an excellent person" 
+7
source

Something like this should be able to do this.

  var text = 'Be an excellent person'; alert(text.replace(/\s\s+/g, ' ')); 
+5
source

You can remove double spaces with the following:

  var text = 'Be an excellent person'; alert(text.replace(/\s\s+/g, ' ')); 

Snippet:

  var text = 'Be an excellent person'; //Split the string by spaces and convert into array text = text.split(" "); // Remove the empty elements from the array text = text.filter(function(item){return item;}); // Join the array with delimeter space text = text.join(" "); // Final result testing alert(text); 
0
source

All Articles