26

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
4

4 Answers 4

37

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

var s = "Be an      excellent     person"
s.replace(/\s{2,}/g, ' ');
1
  • 3
    Note: If you are attempting to remove multiple spaces from (for example) a tab separated file, this will sometimes remove the tabs. That is the only difference between this answer and Yi Jiang's answer.
    – AnnanFay
    Nov 22, 2012 at 18:58
11

This regex should solve the problem:

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

Something like this should be able to do it.

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

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

1
  • How is this different from accepted answer? Why your snippet completly different from code?
    – Toto
    Jun 7, 2019 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.