The Pattern
``regex
\s{2,}|^\s+|\s+$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
leading spaces | ā matches |
trailing spaces | ā matches |
double space inside | ā matches |
this line is already clean | ā rejected |
Three Alternatives, One Pass
\s{2,}|^\s+|\s+$ matches runs of two or more whitespace characters anywhere, plus any
leading or trailing whitespace even when it is a single space. With the m flag the anchors
apply per line, so it cleans a whole document in one replacement.
Replacing every match with a single space collapses internal runs; replacing with an empty
string strips edges. Doing both usually means two passes, or a replacement function that
checks whether the match touched a boundary.
The Limits of This Pattern
\s covers space, tab, newline, carriage return, form feed and vertical tab ā but in
JavaScript it also matches the non-breaking space \u00A0 and various Unicode spaces,
while in some other flavours it does not. Text pasted from a word processor is full of
non-breaking spaces and zero-width characters that look identical to a normal space and
behave differently in comparisons. Normalise explicitly rather than trusting \s to be
the same everywhere.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs ā very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes ā (a+)+, (\w+\s?)* ā can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags ā as here ā they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .
Testing It Properly
`javascript
const pattern = /\s{2,}|^\s+|\s+$/gm;