Regex to Replace Multiple Spaces with a Single Space
Regex to collapse multiple consecutive whitespace characters into a single space. Includes variants for spaces only, all whitespace, and trim-then-collapse.
Detailed Explanation
Replace Multiple Spaces with One
Pasted text, copied tables, and OCR output often contain runs of spaces that should be normalized to a single space.
Collapse Any Run of Whitespace
\s+
text.replace(/\s+/g, " ") replaces every run of whitespace (spaces, tabs, newlines, etc.) with a single space.
Spaces Only (preserve newlines)
[ \t]+
text.replace(/[ \t]+/g, " ") collapses runs of spaces and tabs while keeping line breaks intact.
Tested Examples
| Input | \s+ |
[ \t]+ |
|---|---|---|
"hello world" |
"hello world" |
"hello world" |
"a\t\tb" |
"a b" |
"a b" |
"line1\n\n\nline2" |
"line1 line2" |
"line1\n\n\nline2" |
" leading trailing " |
" leading trailing " |
same |
Trim and Collapse Together
text.replace(/\s+/g, " ").trim()
Or in one regex pass:
text.replace(/^\s+|\s+$|(\s)\s+/g, "$1")
Preserve Paragraph Breaks
If you want to collapse single line breaks but keep blank lines (paragraph separators):
text.replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n")
Performance
\s+ is one of the safest patterns: no nested quantifiers, no alternation. Even on multi-megabyte inputs the regex engine processes it in linear time.
Unicode Whitespace
\s covers ASCII whitespace plus form feed and vertical tab. To also include Unicode space characters (non-breaking space, em space), use the u flag and \p{White_Space}:
text.replace(/\p{White_Space}+/gu, " ")
This catches the troublesome \u00A0 (non-breaking space) commonly pasted from Word.
Use Case
Cleaning user-pasted text in form inputs, normalizing scraped article content for word-count metrics, or sanitizing OCR output before saving to a database.