The Global Flag (g)
You'll learn how to make a regular expression find all matches in a string instead of stopping after the first one.
Finding One vs Finding All
By default, when you use a method like match() or exec(), your regex stops searching after it finds the first match. Think of it like a metal detector that beeps once and then shuts off—you only discover the first coin, even though there might be many more buried nearby.
The global flag (g) changes this behavior. When you append g to your regex pattern, it keeps searching through the entire string to find every occurrence.
How to Use the Global Flag
Add g right after the closing slash of your regex literal:
const text = "cat bat rat";
// Without g: finds only first match
const single = text.match(/at/);
console.log(single); // ["at"]
// With g: finds all matches
const all = text.match(/at/g);
console.log(all); // ["at", "at", "at"]
Notice the difference: without g, you get the first "at" from "cat". With g, you get all three "at" substrings.
When to Use the Global Flag
Use g whenever you need to:
- Find all occurrences of a pattern
- Replace every instance (not just the first)
- Count how many times something appears
Without the global flag, operations typically stop at the first match. With it, they continue until the end of the string.
Key Takeaway: The global flag (g) transforms regex from a "find first" tool into a "find all" tool, enabling you to discover every match in your string rather than stopping after the first one.