What is the meaning of the ‘g’ flag in regular expressions?

g is for global search. Meaning it’ll match all occurrences. You’ll usually also see i which means ignore case.

Reference: global – JavaScript | MDN

The “g” flag indicates that the regular expression should be tested against all possible matches in a string.

Without the g flag, it’ll only test for the first.

Additionally, make sure to check cchamberlain’s answer below for details on how it sets the lastIndex property, which can cause unexpected side effects when re-using a regex against a series of values.

Leave a Comment