Regex for Trimming Leading and Trailing Whitespace

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

Published October 12, 2026

This regex matches whitespace at the start or end of a string so you can remove it with replace.

How the pattern works

Breaking the pattern down: ^\s+ = leading whitespace; \s+$ = trailing whitespace; | = either end.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/^\s+|\s+$/
✓ ' hello'
✓ 'hello '
✗ 'hello'

Practical examples

The pattern

const re = /^\s+|\s+$/

Test it

const re = /^\s+|\s+$/
re.test('  hello')   // true
re.test('hello  ')   // true
re.test('hello')   // false

In Python

import re
re.search(r'^\s+|\s+$', text)

Common mistakes

  • Using regex when String.trim() exists.
  • Forgetting the g flag.
  • Trimming internal spaces unintentionally.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

Simpler way?

str.trim() in JavaScript, str.strip() in Python.

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles