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
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jay Kunitz
  • 261
  • 1
  • 3
  • 3
  • They all seem to work, so I voted them up. Note, I added leading and trailing whitespace to your test string. http://jsfiddle.net/karim79/YhG3h/2/ – karim79 Dec 17 '10 at 02:28
  • 1
    exact duplicate of http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – Recep Dec 29 '10 at 13:58
  • I hope you were placing your wife *up on* a pedestal – David Tedman-Jones Sep 16 '16 at 02:14
  • Possible duplicate of [Regex to replace multiple spaces with a single space](https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space) – KyleMit Dec 01 '17 at 15:59

4 Answers4

37

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

var s = "Be an      excellent     person"
s.replace(/\s{2,}/g, ' ');
KyleMit
  • 30,350
  • 66
  • 462
  • 664
dheerosaur
  • 14,736
  • 6
  • 30
  • 31
  • 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 '12 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"
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
9

Something like this should be able to do it.

 var text = 'Be an      excellent     person';
 alert(text.replace(/\s\s+/g, ' '));
KyleMit
  • 30,350
  • 66
  • 462
  • 664
RageZ
  • 26,800
  • 12
  • 67
  • 76
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);
 
 
Kevin
  • 2,258
  • 1
  • 32
  • 40
Lokesh
  • 39
  • 3
  • How is this different from accepted answer? Why your snippet completly different from code? – Toto Jun 07 '19 at 10:06