Regex to Trim Leading and Trailing Whitespace
This pattern matches a run of whitespace at the very start of a string or at the very end. Replace every match with nothing — text.replace(/^\s+|\s+$/g, "") — and the string is trimmed. Most languages have trim() built in, so reach for the regex form where only regex replacement is available: editors, SQL REGEXP_REPLACE, config-driven pipelines.
/^\s+|\s+$/How it works, token by token
| Token | Meaning |
|---|---|
| ^\s+ | one or more whitespace characters at the start of the string |
| | | or |
| \s+$ | one or more whitespace characters at the end of the string |
What it matches
paddedtrailing both cleaninner spaceTry it live
One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.
Variations
\s{2,}two or more whitespace characters anywhere — replace with one space to collapse runs^[ \t]+|[ \t]+$spaces and tabs only, leaving line breaks aloneLanguage notes
- Without the g flag, JavaScript's replace() removes only the first match — the leading or the trailing run, not both. Python's re.sub replaces all matches by default.
- With the m (multiline) flag, ^ and $ match at every line, so the pattern trims each line instead of the whole string.
Frequently asked questions
Is trim() better than this regex?
Usually — String.prototype.trim() in JavaScript, str.strip() in Python and strings.TrimSpace in Go are clearer and faster. Use the regex where only regex replacement is available.
Does \s match non-breaking spaces?
In JavaScript, yes: \s covers Unicode spaces including U+00A0. Some other engines treat \s as ASCII-only, so pasted text with non-breaking spaces may survive the trim there.
Building something custom? The regex tester gives you live match highlighting for any pattern.