Whitespace regex

Regex to trim leading and trailing whitespace, collapse repeated spaces and remove blank lines. With replace examples.

Pattern
/[ \t]{2,}/g

Matches

  • a b
  • tab here
  • x y

Doesn't match

  • a b
  • single
  • no-spaces

Alternative: Blank lines (use with g and m)

^\s*$\n

Notes

  • Collapse runs of spaces: text.replace(/[ \t]{2,}/g, " ").
  • Trim: text.replace(/^\s+|\s+$/g, "") — or just text.trim().
  • \s also matches newlines; use [ \t] when you want to keep line breaks.

Code

JavaScript

const re = /[ \t]{2,}/g;
const all = text.match(re);

Python

import re

re.findall(r'[ \t]{2,}', text)

Try it on your own input

The live tester adds the g and m flags so every line is checked separately.

Questions

What does \s match exactly?

In JavaScript: space, tab, newline, carriage return, vertical tab, form feed and Unicode spaces such as the no-break space (U+00A0).

More patterns

Email regexPhone number regexURL regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regex