Regex for leading and trailing whitespace

/^[ \t]+|[ \t]+$/gm

Options
Matches

Examples

Note

With the m flag, ^ and $ work per line. Replace with nothing to trim every line.

Matches in the example

  • " "
  • " "
  • "\t"
  • " "

Token by token

  1. ^ the start of the string (or line, with the m flag)
  2. [ \t]+ one of: a space or a tab, one or more times, as many as possible
  3. | or
  4. [ \t]+ one of: a space or a tab, one or more times, as many as possible
  5. $ the end of the string (or line, with the m flag)

Other patterns