RegexBuilder · regex answers
Regex to trim leading and trailing whitespace
/^\s+|\s+$/g
Two alternatives — whitespace at the start, whitespace at the end — replaced with nothing. Modern runtimes have a trim method that is faster and clearer; reach for this when you are inside a tool that only offers find-and-replace.
What each part does
| ^\s+ | a run of whitespace anchored to the start |
| | | or |
| \s+$ | a run of whitespace anchored to the end |
| g | global, so both ends are handled in one pass |
Tested against real input
Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.
| Input | Result | Matched |
|---|---|---|
| hello | matches | |
| \thello\n | matches | \t |
| hello | no match | — |
The mistake to avoid
Forgetting the global flag. Without it only the leading run is replaced and the trailing spaces survive.
Try it on your own text
Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.
Open RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex for a UUID
- Regex for a hex colour code