JavaScript / ECMAScript

Whitespace Trim (Leading & Trailing) in JS

Match leading and/or trailing whitespace on a string — the regex equivalent of .trim().

Try it in the JS tester →

Pattern

regexJS
^\s+|\s+$   (flags: g)

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

How the pattern 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

Same pattern, other engines

← Back to Whitespace Trim (Leading & Trailing) overview (all engines)