Regex to replace multiple spaces with a single space
Given that you also want to cover tabs, newlines, etc, just replace \s\s+
with ' '
:
string = string.replace(/\s\s+/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, ' ' ) -> 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.)
var str = "The dog has a long tail, and it is RED!";
str = str.replace(/ {2,}/g,' ');
EDIT: If you wish to replace all kind of whitespace characters the most efficient way would be like that:
str = str.replace(/\s{2,}/g,' ');
A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:
// NOTE the possible initial and trailing spaces
var str = " The dog has a long tail, and it is RED! "
str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// str -> "The dog has a long tail, and it is RED !"
Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.