Regex to replace multiple spaces with a single space

后端 未结 23 2757
北恋
北恋 2020-11-22 10:00

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 o

23条回答
  •  天命终不由人
    2020-11-22 10:16

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

    str.replace( /  +/g, ' ' )       ->  380ms
    str.replace( /\s\s+/g, ' ' )     ->  390ms
    str.replace( / {2,}/g, ' ' )     ->  470ms
    str.replace( / +/g, ' ' )        ->  790ms
    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.)

提交回复
热议问题