Course contentsShow
← JavaScript
Lesson 166 of 2,7235. StringsFree lesson

Global vs Non-Global Regex Matches

Learn how the 'g' flag affects match() results and when to use match() vs matchAll().

Global vs Non-Global Regex Matches

You'll learn how the 'g' flag changes what match() returns and when to choose match() vs matchAll().

What the 'g' Flag Does

When you use match() with a regular expression, the global flag ('g') dramatically changes the behavior:

Without 'g' (non-global): match() returns an array with the first match plus extra details like the index and captured groups.

With 'g' (global): match() returns an array of all matching strings, but loses the extra details (no indices, no captured groups).

Think of it like searching a book: without 'g', you find the first occurrence and bookmark the exact page. With 'g', you list every occurrence but skip the page numbers.

Examples

const text = "cat bat rat cat";

// Non-global: first match + details
const nonGlobal = text.match(/cat/);
console.log(nonGlobal); // ["cat", index: 0, input: "cat bat rat cat", ...]

// Global: all matches, no details
const global = text.match(/cat/g);
console.log(global); // ["cat", "cat"]

When to Use What

  • Use non-global match() when you need the first occurrence with position info
  • Use global match() when you want a simple list of all matches
  • Use matchAll() when you need all matches with details (indices, groups)
// matchAll gives you the best of both worlds (but needs 'g')
const allDetails = text.matchAll(/cat/g);
for (const match of allDetails) {
  console.log(match[0], "at index", match.index);
}
// "cat at index 0"
// "cat at index 12"

Key Takeaway: The 'g' flag makes match() return all matches instead of just the first, but you lose detail—use matchAll() when you need both completeness and context.