views:

185

answers:

3

How can I automatically replace all multiple spaces with one single space in Javascript?

I've tried with just chaining some s.replace but this doesn't seem optimal.

I'm using jQuery as well in case it's a builtin functionality.

+1  A: 

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space

Josiah
This works too.s = s.replace(/ +/g, " ");
InfinitiesLoop
Very true :) --inserts more characters--
Josiah
+2  A: 

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space

Greg Shackles
A: 

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');
kennebec