text = text.replace(/\s{2,}/g, ' ');
\s will accept all spaces, including newlines, so you can change this to / {2,}/g .{2,} takes two or more. Unlike \s+ , this does not replace one space with one space. (a bit of optimization, but usually it makes a difference).- Finally, the
g flag is required in JavaScript, or it will only change the first block of spaces, not all of them.
source share