如何在 Javascript 中用一个空格自动替换多个空格的所有实例?
我已经尝试链接一些 s.replace,但这似乎不是最佳的。
s.replace
我也在使用 jQuery,以防它是一个内置功能。
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
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
You can also replace without a regular expression.
while(str.indexOf(' ')!=-1)str.replace(' ',' ');
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, ' ');