/g (Global)
What is /g (Global)?
/g (Global): Match all occurrences in the string, not just the first one. The g flag makes a regular expression find every match, not just the first. In JavaScript, 'a-b-c'.replace(/-/g, '+') returns a+b+c. Without g you get a+b-c. It also changes how some methods behave. str.match(/x/g) returns an array of all matches, while without g it returns details about the first match only. For all matches with their capture groups, use str.matchAll(), which requires the g flag.
Frequently asked questions about /g (Global)
What should you keep in mind with /g (Global)?
Watch out for one trap. A regex object with g remembers where it stopped in its lastIndex property. Calling regex.test() twice on different strings with the same object can then give a surprising false. If you reuse a global regex, reset lastIndex or create the regex inside the function. Modern JavaScript also offers replaceAll() for plain text replacements.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |