JS: Regex Flag g (global)

By Xah Lee. Date: . Last updated: .

What is rgex flag g (global)

depending on regex function, flag g may mean find/do all matches, or move regexObj.lastIndex and search again from there.

Find/do all matches

for these regex functions:

the g flag means find all occurrences.

// with flag g
console.log(
 "j3194 b1303 c2610".match(/(.)\d\d\d\d/g),
);
// [ "j3194", "b1303", "c2610" ]

// without flag g
console.log(
 "j3194 b1303 c2610".match(/(.)\d\d\d\d/),
);
// [ "j3194", "j", index: 0, input: "j3194 b1303 c2610", groups: undefined ]

Set and start at lastIndex

for these regex functions:

the g flag means sets regexObj.lastIndex and start search from there when the regex object is used again.

// with regex flag g. lastIndex is advanced or set to 0.
// test with RegExp.prototype.exec

const xtext = "012-45-78-";
const rgx = /-/g;
console.assert(rgx.lastIndex === 0);

console.log(rgx.exec(xtext));
// [ "-", index: 3, input: "012-45-78-", groups: undefined ]

console.assert(rgx.lastIndex === 4);

console.log(rgx.exec(xtext));
// [ "-", index: 6, input: "012-45-78-", groups: undefined ]

console.assert(rgx.lastIndex === 7);

Regexp.prototype.global

RegExp.prototype.global is a Getter Property. Value is true if flag g is set, on the given regex object.

const rgx = /some/g;
console.assert(rgx.global === true);