在JavaScript /正则表达式中,如何删除字符串中的双空格?
问题描述:
如果我有多个空格的字符串单词之间:使用JavaScript /正则表达式,如何删除多余的内部空间,使之成为在JavaScript /正则表达式中,如何删除字符串中的双空格?
Be an excellent person
:
Be an excellent person
答
像这样的东西应该能去做吧。
var text = 'Be an excellent person';
alert(text.replace(/\s\s+/g, ' '));
答
此正则表达式应该解决的问题:
var t = 'Be an excellent person';
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"
答
您可以使用正则表达式/\s{2,}/g
:
var s = "Be an excellent person"
s.replace(/\s{2,}/g, ' ');
+0
注意:如果您试图从(例如)制表符分隔的文件中删除多个空格,则有时会删除制表符。这是答案和伊江答案之间的唯一区别。 – Annan 2012-11-22 18:58:50
他们似乎都工作,所以我投了起来。请注意,我在测试字符串中添加了前导空格和尾部空格。 http://jsfiddle.net/karim79/YhG3h/2/ – karim79 2010-12-17 02:28:14
http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – Recep 2010-12-29 13:58:34
我希望你把你的妻子*放在一个基座上 – 2016-09-16 02:14:04