# Regex to Trim Leading and Trailing Whitespace

> The regex ^\s+|\s+$ finds whitespace at the start or end of a string, for trimming with replace(). Plus a variation to collapse inner spaces, explained.

```
/^\s+|\s+$/
```

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.

## 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 |

## Examples

- ✓ matches: `  padded`
- ✓ matches: `trailing  `
- ✓ matches: `  both  `
- ✗ does not match: `clean`
- ✗ does not match: `inner space`

## 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 alone

## Language 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.

## FAQ

### 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.

## Related patterns

- [Regex for URL Slug Validation](https://www.devkult.com/regex/slug.md)
- [Regex for Alphanumeric Strings](https://www.devkult.com/regex/alphanumeric.md)
- [Regex for HTML Tags](https://www.devkult.com/regex/html-tag.md)

Open the interactive page: https://www.devkult.com/regex/trim-whitespace