How-to

How to Match Whitespace in Regex

\s matches any whitespace — space, tab, newline, and more. Use \s+ to collapse runs, ^\s*$ to detect blank lines, and \S for non-whitespace.

The whitespace shorthand

\s matches one whitespace character: space, tab (\t), newline (\n), carriage return (\r), form feed, vertical tab, and several Unicode whitespace characters. \S is the negation: any character that isn't whitespace.

Collapse runs of whitespace

Try this
/\s+/g

Input

one two\t\tthree

Result

3 matches; replace with ' ' for single-space collapse

Detect blank lines

^\s*$ with the m flag finds lines containing only whitespace (or nothing). Useful when cleaning up markdown, config files, or email bodies where extra blank lines have piled up.

Trim leading and trailing whitespace

A common trim replace uses two patterns: /^\s+|\s+$/g. The alternation matches either leading or trailing whitespace, and the g flag handles both in one pass. (Modern JavaScript has String.trim — regex matters if you're trimming something other than a full string, like each element of a pipe-delimited list.)

Trim pattern

Try this
/^\s+|\s+$/g

Input

hello world

Result

After replace → 'hello world'

Whitespace-only line detection

If you want to match truly EMPTY lines (no characters at all, not even spaces), use ^$ instead of ^\s*$. The former is stricter; use it when you want to preserve lines that are just a tab, for example.

Related patterns

All reference guidesOpen the RegexPro tester →