Course contentsShow
← JavaScript
Lesson 1722 of 2,72336. Regular ExpressionsFree lesson

The Global Flag and Match Behavior

How the 'g' flag changes regex behavior for methods like match(), exec(), and replaceAll().

The Global Flag and Match Behavior

You'll learn how the g flag fundamentally changes how regex methods behave — from single-match to multi-match mode.


Why the Global Flag Matters

The global flag (g) doesn't just affect what you find — it changes how methods iterate through a string. Without g, most methods stop after the first match. With g, they keep searching from where they left off.

How g Affects match()

Without g: str.match(regex) returns an array with the first match plus any capture groups.

With g: It returns an array of all matches (no capture groups included!).

const text = "cat bat rat";

text.match(/\w+at/);   // ["cat"] (first match only)
text.match(/\w+at/g);  // ["cat", "bat", "rat"] (all matches)

How g Affects exec()

The exec() method uses a stateful cursor called lastIndex when g is set. Each call advances to the next match:

const regex = /\d+/g;
const text = "10 20 30";

regex.exec(text);  // ["10"]
regex.exec(text);  // ["20"]  (continues from where it left off)
regex.exec(text);  // ["30"]
regex.exec(text);  // null (resets)

Without g, exec() always starts from the beginning.

How g Affects replaceAll()

The replaceAll() method requires the g flag when using regex. Without it, you'll get an error:

"ha ha ha".replaceAll(/ha/g, "ho");  // "ho ho ho" ✓
"ha ha ha".replaceAll(/ha/, "ho");   // TypeError ✗

Key Takeaway: The global flag (g) switches regex methods from single-match to multi-match mode, changes match() output structure, makes exec() stateful, and is required for replaceAll() when using patterns.