breakitdown

Regex to trim leading and trailing whitespace

Answer

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.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

Slow on long input. \s+$ is not anchored at the start, so when searching, the engine tries it from every position in a long run of matching characters that is not at the end of the string: quadratic time. This exact pattern (\s+$) took Stack Overflow down in 2016. Anchor it, use a built-in such as trimEnd(), or check the end of the string with a loop.
  1. |Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation
  2. Alternative 1:
  3. ^Start of the stringanchor
  4. \sA whitespace character (space, tab, line break and other Unicode spaces)character type
  5. +Repeat it one or more times, as many as possible (greedy)quantifier
  6. Alternative 2:
  7. \sA whitespace character (space, tab, line break and other Unicode spaces)character type
  8. +Repeat it one or more times, as many as possible (greedy)quantifier
  9. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
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

Gotchas

Related explainers

← Explain any regular expression