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()
Related patterns
Trailing Whitespace (Per Line)
Text ProcessingMatch trailing spaces and tabs at the end of each line — the regex linters use to flag dirty whitespace.
Whitespace-Only Line
Text ProcessingMatches lines containing only whitespace (or empty lines).
JSON Number (Strict)
Text ProcessingMatch JSON-spec numbers — disallows leading zeros (no `01`), allows decimals and exponents.
Sentence Boundary
Text ProcessingMatches sentence boundaries (punctuation followed by whitespace and a capital letter).