开发者

Remove all multiple spaces in Javascript and replace with single space [duplicate]

开发者 https://www.devze.com 2023-01-08 04:35 出处:网络
This question already has answers here: Regex to replace multiple spaces with a single space (26 answers)
This question already has answers here: Regex to replace multiple spaces with a single space (26 answers) Closed 8 years ago.

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.


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 all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp

here best solution

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


You can also replace without a regular expression.

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

精彩评论

暂无评论...
验证码 换一张
取 消