如何使用正则表达式去除双空白字符?
答
text = text.replace(/\s{2,}/g, ' ');
-
\s
将采取一切空间,包括新线,所以你可能会改变,要/ {2,}/g
。 -
{2,}
需要两个或更多。与\s+
不同,这不会用单个空间替代单个空间。 (有点优化,但通常有差异) - 最后,在JavaScript中需要
g
标志,否则它只会改变第一块空格,而不是所有的空格。
+0
谢谢,那就是我需要的。 – faressoft 2010-08-31 12:45:38
答
在PCRE:
s/\s+/ /g
在JavaScript:
text = text.replace(/\s+/g, " ");
+1
我不知道是谁投我的票。 我的回答有什么问题? – polemon 2010-08-31 13:24:42
答
尝试
result = str.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
+1
+1用于修剪。 – SLaks 2010-08-31 12:40:51
答
var str="this is some text with lots of spaces!";
var result =str.replace(/\s+/," ");
学习最好的办法是做它,尝试HTTP:/ /www.gskinner.com/RegExr/用于测试 – 2010-08-31 12:38:50
真是太棒了,谢谢。 – faressoft 2010-08-31 12:42:44
[Regular Expression Pocket Reference,Second Edition](http://oreilly.com/catalog/9780596514273?green=13581578926&cmp=af-mybuy-9780596514273.IP)是一本相当不错的书。后背的口袋很好用(如果你有甜美的牛仔裤)。 – hellozimi 2010-08-31 12:50:58