Remove all multiple spaces in Javascript and replace them with a single space

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

I tried linking several s.replace , but this does not seem optimal.

I also use jQuery if it is built-in functionality.

+49
javascript jquery replace
Jul 20 2018-10-10T00:
source share
4 answers

You can use the regular expression replace:

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

Credit: the above regex was taken from Regex to replace multiple spaces with one space

+102
Jul 20 2018-10-10T00:
source share

There are many regex options that you could use to achieve this. One example that will work well:

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

See this question for a full discussion of this exact problem: Regex replace multiple spaces with a single space

+30
Jul 20 2018-10-10T00:
source share

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

here is the best solution

 str = str.replace(/\s{2,}/g, ' '); 
+16
Dec 27 '12 at 10:38
source share

You can also replace without regex.

 while(str.indexOf(' ')!=-1)str.replace(' ',' '); 
+2
Jul 20 '10 at 4:09
source share



All Articles