Regex patterns/Text & extraction

Trim leading and trailing whitespace

Two anchored alternatives in one pass — the classic trim, per line.

/^\s+|\s+$/gm
Open it in Rex

The problem

Strip the spaces and tabs at the start and end of every line, leaving the text between them alone.

How it reads

start\srepeat\srepeatend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^\s+|\s+$Any one of these alternatives:
  2. ^\s+In order:
  3. ^The start of the text (or of a line with the m flag)
  4. \s+Whitespace, one or more times, as many as possible
  5. \s+$In order:
  6. \s+Whitespace, one or more times, as many as possible
  7. $The end of the text (or of a line with the m flag)

Matches

  • padded
  • trailing

Does not match

  • clean
  • inner space

Where it bites

  • Without the g flag you replace only the leading whitespace; both alternatives need to fire.
  • The m flag is what makes ^ and $ mean "each line" rather than "the whole string".
  • For a single string in JavaScript, value.trim() is faster and clearer. This earns its place when trimming every line of a block at once.

More text & extraction patterns