DELAPARRA
Index
Color
NL
Category: Regex flags

/g (Global)

Explained by Updated

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.

Definition source Coders Lingo, CC BY 4.0

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

CategoryRegex flags
Explained by
Updated

More Regex flags terms

All terms starting with a number or symbol

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.