RegExp global flag (g)

Makes a regular expression find all matches rather than stopping at the first.

Since ES3 Spec ↗

Syntax

/pattern/g

Examples

console.log("a1b2c3".match(/\d/g));
Output
[ '1', '2', '3' ]
console.log("a.b.c".replace(/\./g, "-"));
Output
a-b-c
console.log([..."x1y2".matchAll(/\d/g)].map(m => m[0]));
Output
[ '1', '2' ]

Notes

- With `g`, `String.prototype.match()` returns all matches but no groups; use `matchAll()` for groups. - A global regex is stateful via `lastIndex` when using `exec`/`test`. - `replace()` with `g` replaces every occurrence.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also