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

本秂侑毒 提交于 2019-11-27 00:00:46

问题


This question already has an answer here:

  • Regex to replace multiple spaces with a single space 21 answers

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.


回答1:


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




回答2:


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




回答3:


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, ' ');



回答4:


You can also replace without a regular expression.

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


来源:https://stackoverflow.com/questions/3286874/remove-all-multiple-spaces-in-javascript-and-replace-with-single-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!