Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have a string with multiple spaces between words:

Be an      excellent     person

using JavaScript/regex, how do I remove extraneous internal spaces so that it becomes:

Be an excellent person
like image 886
Jay Kunitz Avatar asked Dec 17 '10 01:12

Jay Kunitz


4 Answers

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

var s = "Be an      excellent     person"
s.replace(/\s{2,}/g, ' ');
like image 53
dheerosaur Avatar answered Sep 22 '22 19:09

dheerosaur


This regex should solve the problem:

var t = 'Be an      excellent     person'; 
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"
like image 43
Yi Jiang Avatar answered Sep 19 '22 19:09

Yi Jiang


Something like this should be able to do it.

 var text = 'Be an      excellent     person';
 alert(text.replace(/\s\s+/g, ' '));
like image 44
RageZ Avatar answered Sep 20 '22 19:09

RageZ


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);
 
 
like image 40
Lokesh Avatar answered Sep 20 '22 19:09

Lokesh