在 JavaScript/regex 中,如何删除字符串中的双空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4467024/
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
In JavaScript/regex, how do you remove double spaces inside a string?
提问by Jay Kunitz
If I have a string with multiple spaces between words:
如果我有一个单词之间有多个空格的字符串:
Be an      excellent     person
using JavaScript/regex, how do I remove extraneous internal spaces so that it becomes:
使用 JavaScript/regex,如何删除无关的内部空间,使其变为:
Be an excellent person
回答by dheerosaur
You can use the regex /\s{2,}/g:
您可以使用正则表达式/\s{2,}/g:
var s = "Be an      excellent     person"
s.replace(/\s{2,}/g, ' ');
回答by Yi Jiang
This regex should solve the problem:
这个正则表达式应该可以解决问题:
var t = 'Be an      excellent     person'; 
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"
回答by RageZ
Something like this should be able to do it.
像这样的东西应该可以做到。
 var text = 'Be an      excellent     person';
 alert(text.replace(/\s\s+/g, ' '));
回答by Lokesh
you can remove double spaces with the following :
您可以使用以下方法删除双空格:
 var text = 'Be an      excellent     person';
 alert(text.replace(/\s\s+/g, ' '));
Snippet:
片段:
 var text = 'Be an      excellent     person';
 //Split the string by spaces and convert into array
 text = text.split(" ");
 // Remove the empty elements from the array
 text = text.filter(function(item){return item;});
 // Join the array with delimeter space
 text = text.join(" ");
 // Final result testing
 alert(text);
 
 

