123

How can I automatically replace all instances of multiple spaces, with a single space, in Javascript?

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

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

0

4 Answers 4

260

You could use a regular expression replace:

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

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

Sign up to request clarification or add additional context in comments.

9 Comments

This works too. s = s.replace(/ +/g, " ");
Very true :) --inserts more characters--
str= ''+str.replace(/ +(?= )/g,'') is little better solution in case your str is undefinied or NaN :)
i'm reading data in from a txt file (via AJAX), and @InfinitiesLoop regex worked fine but Josiah's didn't
This didnt work for me. However @redexp did.
|
62

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: Regex to replace multiple spaces with a single space

Comments

47

you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp

here best solution

str = str.replace(/\s{2,}/g, ' ');

6 Comments

You could also cite Regular Expression website for all sorts of regex flavors and full reference.
What's the improvement in using bracket quantifier over a simple +?
@some-non-descript-user /\s+/g also replaces single spaces (there is no need for this) but /\s\s+/g or /\s{2,}/g replace only multiple spaces.
@Aalex Gabi: sure, you're right, but, aesthetics aside, I doubt this will be noticeable in the vast majority of applications. A slight performance gain in veery large files, maybe? In all other cases, the plus is more convenient than the brackets, I'd say.
@some-non-descript-user I agree that the + is more convenient than the brackets. As for performance the single space is one third slower than the double space: jsperf.com/removing-multiple-spaces
|
5

You can also replace without a regular expression.

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

3 Comments

Works too... The question is : which is more efficient? This version or the regex version. I have a preference for regex as we never practice enough.
I don't know- if you have no matches, this method is more efficient. If you have a lot of matches, somebody is doing it wrong.
Here's a fiddle that, I hope, emphasize the difference. It clearly outputs that regular expressions are, in all cases, at least as fast as loop versions. Not saying that loop version is bad, just pointing out that one must always consider maintainability and evolution of product.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.