Regex to Match Whitespace
Copy the pattern, paste your text, and watch every space, tab and line break light up. Below: what \s matches and how to collapse runs.
What this pattern matches
\s+ matches one or more whitespace characters in a row: regular spaces, tabs (\t), newlines (\n), carriage returns and vertical tabs. The + groups consecutive whitespace into a single match, which is exactly what you want when collapsing messy spacing.
Collapse runs to a single space
Replace every match with one space: text.replace(/\s+/g, ' '). To also trim the ends, add .trim().
Match only horizontal whitespace
If you must keep line breaks, use [ \t]+ instead of \s+ so newlines are left untouched.
FAQ
Does \s match newlines?
Yes. \s covers spaces, tabs, newlines, carriage returns, form feeds and vertical tabs. Use [ \t] if you want horizontal whitespace only.
How do I collapse multiple spaces into one?
Replace /\s+/g with a single space, then .trim() the result.
Why use + after \s?
Without +, each whitespace character is a separate match. With +, a run of spaces or a tab-plus-space becomes one match, which is what you want for cleanup.