Javascript 删除Javascript中的所有多个空格并替换为单个空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3286874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all multiple spaces in Javascript and replace with single space
提问by Alex
How can I automatically replace all instances of multiple spaces, with a single space, in Javascript?
如何在 Javascript 中用一个空格自动替换多个空格的所有实例?
I've tried chaining some s.replacebut this doesn't seem optimal.
我试过链接一些,s.replace但这似乎不是最佳的。
I'm using jQuery as well, in case it's a builtin functionality.
我也在使用 jQuery,以防它是一个内置功能。
回答by Josiah
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
信用:上述正则表达式取自Regex 用单个空格替换多个空格
回答by Greg Shackles
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
有关此确切问题的完整讨论,请参阅此问题:Regex to replace multiple space with a single space
回答by redexp
you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp
你们都忘记了量词 n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp
here best solution
这里最好的解决方案
str = str.replace(/\s{2,}/g, ' ');
回答by kennebec
You can also replace without a regular expression.
您也可以在没有正则表达式的情况下进行替换。
while(str.indexOf(' ')!=-1)str.replace(' ',' ');

