Regex for Trimming Leading and Trailing Whitespace

Matches whitespace at the very start or end of a string.

Published October 12, 2026

Matches whitespace at the very start or end of a string.

Key points

  • Most languages have a built-in trim() function that's simpler and more reliable than this regex for the common case

Example

^\s+|\s+$
More General articles