How the pattern works
| Part | Meaning |
|---|---|
^\s+ | Whitespace at the start |
| | or |
\s+$ | Whitespace at the end |
g flag | Replace both, not just the first |
Code examples
JavaScript
const out = text.replace(/^\s+|\s+$/g, "");Python
import re
out = re.sub(r'^\s+|\s+$', r'', text)PHP
$out = preg_replace('/^\s+|\s+$/', '', $text);
Notes and limitations
In modern code, str.trim() (JavaScript), s.strip() (Python) and trim() (PHP) do the same thing; the regex is useful in editors and tools that only offer find-and-replace. Add the m flag to trim every line. Try it in Find and Replace.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex to trim leading and trailing whitespace?
/^\s+|\s+$/g — it is used with find and replace. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.