Skip to main content
hank-builds.com

Whitespace Trimming regex

Matches leading and trailing whitespace.

/^\s+|\s+$/gm

What it matches

Runs of whitespace at the start or the end of a line, as two alternatives sharing one pattern. With the m flag the anchors bind to each line rather than the whole string, so a single replace with an empty string trims every line in a block of text at once.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

^ \s \s $

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
m^ and $ match the start/end of each line, not just the string
^Start of string
\s+Whitespace, one or more
\s+Whitespace, one or more
$End of string

Test cases

Matches

  • leading
  • trailing
  • tabbed

Does not match

  • clean
  • inner spaces here

Caveats

\s covers tabs, form feeds and Unicode spaces as well as the plain space, which is usually what you want but will also eat a non-breaking space that was there deliberately. It leaves interior runs alone; collapsing those needs a separate \s+ pass. Without the m flag it trims only the ends of the whole string.

More text processing patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.