RRegexBuilder
Get RegexBuilder

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
gglobal, 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.

InputResultMatched
hello matches
\thello\nmatches\t
hellono 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 RegexBuilder

Other regex answers