Regex to replace multiple spaces with a single space

Given a string like:

"The dog      has a long   tail, and it     is RED!"

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

Goal:

"The dog has a long tail, and it is RED!"

Given that you also want to cover tabs, newlines, etc, just replace ss+ with ' ' :

string = string.replace(/ss+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:

str.replace( / +/g, ' ' )        ->  790ms
str.replace( /  +/g, ' ' )       ->  380ms
str.replace( / {2,}/g, ' ' )     ->  470ms
str.replace( /ss+/g, ' ' )     ->  390ms
str.replace( / +(?= )/g, ' ')    -> 3250ms

This is on Firefox, running 100k string replacements.

I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.

(Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)


var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

编辑:如果你想要替换所有类型的空白字符,最有效的方式将是这样的:

str = str.replace(/s{2,}/g,' ');
链接地址: http://www.djcxy.com/p/74148.html

上一篇: JavaScript跨浏览器脚本帮助

下一篇: 正则表达式用一个空格替换多个空格