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).

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 padding

No 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