Regex to Replace Repeated Whitespace

All patterns
Replace3 chars · /g

Regex to Replace Repeated Whitespace

Use this before `.replace()` when normalizing messy copy, scraped text, or imported CSV fields with inconsistent spacing.

The expression

/\s+/g

How to read it

\s matches any whitespace, including tabs and newlines.

gglobal — keep going after the first match instead of stopping

Find matches in your own text

no input
Try:

This expression is unanchored, so it finds every occurrence anywhere in the text. Highlighted runs are what a replace call would rewrite.

Examples, checked in your browser

4/4 verified

too many spaces

Matches 2 times.

line breaks count too

Matches 3 times.

single-space

No match — this is the kind of input the pattern rejects.

clean

No match — this is the kind of input the pattern rejects.

Use it in code

3 languages
JavaScript
const regex = /\s+/g;
regex.test(input);
Python
import re
pattern = re.compile(r"\s+")
bool(pattern.search(input))
Go
re := regexp.MustCompile("\\s+")
matched := re.MatchString(input)

Other replace patterns

3
GroupReplace
Flags/g
Examples4
SafetyOK