Text Processingflags: g
Whitespace Trim (Leading & Trailing)
Match leading and/or trailing whitespace on a string — the regex equivalent of .trim().
Try it in RegexPro →Available in
Pattern
regexengine-agnostic
^\s+|\s+$ (flags: g)Raw source: ^\s+|\s+$
How it works
^\s+ matches one or more whitespace characters at the start of the string. \s+$ matches one or more whitespace characters at the end. The alternation | with the g flag allows replacing both in a single pass.
Examples
Input
hello world Matches
Input
tabbed Matches
Input
no paddingNo match
—Common use cases
- •Pre-processing form input before storage
- •CSV/TSV data cleaning pipelines
- •Template output normalization
- •String sanitization in older JS environments without .trim()