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
JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("^\\s+|\\s+$", "g");
const input = " hello world ";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
pyPython
import re
pattern = re.compile(r"^\s+|\s+$")
input_text = " hello world "
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\s+|\s+$`)
input := ` hello world `
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
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).