Regex to trim leading and trailing whitespace
s.replace(/^\s+|\s+$/g, "") removes whitespace at the start and end of a string. The g flag is required, or only the first of the two matches is replaced. In modern JavaScript use s.trim(), which does the same thing faster.
JavaScript ✓PCRE ✓
|Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation- Alternative 1:
^Start of the stringanchor\sA whitespace character (space, tab, line break and other Unicode spaces)character type+Repeat it one or more times, as many as possible (greedy)quantifier- Alternative 2:
\sA whitespace character (space, tab, line break and other Unicode spaces)character type+Repeat it one or more times, as many as possible (greedy)quantifier$End of the stringanchor
Examples
Checked at build time in JavaScript and in Python's re.
| Input | Matches? |
|---|---|
hello | ✓ match |
hello | ✓ match |
hello | ✓ match |
hello world | ✗ no match |
hello | ✗ no match |
(empty string) | ✗ no match |
| ✓ match |
Try your own text
One string per line: each line is tested on its own (the m flag is added here).
How it works
The alternation has two branches: whitespace anchored at the start, and whitespace anchored at the end. Without g, replace stops after the leading run and leaves the trailing spaces.
The second branch has a performance trap. \s+$ is tried at every position. On a string with a long run of spaces in the middle, the engine matches the run, finds no end of string after it, and starts again one character later. That is quadratic time. On July 20, 2016, a post containing about 20,000 consecutive whitespace characters made a similar trim regex take Stack Overflow down for 34 minutes. trim() scans from each end and has no such problem.
Variants
/\s+/gCollapse internal runs:s.trim().replace(/\s+/g, " ")normalizes all whitespace to single spaces./^[ \t]+|[ \t]+$/gmStrip spaces and tabs at the start and end of every line, leaving line breaks alone.
Gotchas
\s+$costs time proportional to n squared on strings with long runs of inner whitespace. Usetrim(), ortrimStart()andtrimEnd(), on untrusted input.- With the
mflag,^and$match at every line, so the regex also strips whitespace at the end of each line. Sometimes that is what you want; often it is a surprise. - JavaScript's
\sincludes the no-break space (U+00A0) and the byte-order mark (U+FEFF). Python's\sdoes not include U+FEFF. Code ported between the two can disagree on text pasted from Word or Windows files. - Calling
.test()on a regex with thegflag is stateful: it advanceslastIndex, so a second call on the same string can return false. Usegonly forreplaceandmatchAll.
Related explainers
- Catastrophic backtracking, explained with ^(a+)+$Why ^(a+)+$ takes exponential time on input like aaaa...b, how nested quantifiers cause ReDoS, and the...
- Regex to find repeated words ("the the")Find doubled words like "the the" with a backreference, why word boundaries matter, and the cases where...
- Regex for an email addressA practical email regex, why a fully RFC 5322-correct one is not worth it, what HTML5's type=email...