在JavaScript/正则表达式中,如何删除字符串内部的双空格?

26
如果我有一个包含多个空格的字符串:
Be an      excellent     person

使用 JavaScript / 正则表达式,如何删除多余的内部空格,使其变为:

Be an excellent person

它们似乎都能正常工作,所以我给它们投了赞成票。注意,我在你的测试字符串中添加了前导和尾随空格。http://jsfiddle.net/karim79/YhG3h/2/ - karim79
1
正则表达式用于将多个空格替换为单个空格。 - Recep
我希望你把你的妻子看得很重要。 - David Tedman-Jones
4个回答

37

您可以使用正则表达式:/\s{2,}/g

var s = "Be an      excellent     person"
s.replace(/\s{2,}/g, ' ');

3
注意:如果你试图从(例如)一个制表符分隔的文件中去除多个空格,有时会同时去除制表符。这是这个答案和Yi Jiang的答案之间唯一的区别。 - AnnanFay

11
这个正则表达式应该解决问题:
var t = 'Be an      excellent     person'; 
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"

9
像这样的东西应该能够做到。
 var text = 'Be an      excellent     person';
 alert(text.replace(/\s\s+/g, ' '));

3

您可以使用以下方法去除双空格:

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


这与被接受的答案有何不同?为什么你的代码片段完全不同? - Toto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接