JavaScript RegExp g Modifier

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Global flag

What You’ll Learn

The g modifier (global flag) tells the regex engine to find every match in a string—not stop after the first hit. It powers replace-all workflows, matchAll(), and exec() loops that walk through all occurrences.

01

g flag

Find all

02

global

RegExp prop

03

lastIndex

Advances

04

match()

All strings

05

replace

/pat/g

06

matchAll

Needs g

Introduction

By default, many regex operations stop after the first successful match. Add the g modifier when you need to process all occurrences—counting words, replacing every match, or collecting every date in a log file.

The global flag changes how exec(), test(), match(), and replace() behave. It also sets the global property on the RegExp object to true, which you can inspect at runtime.

Understanding the g Modifier

Append g to a regex literal or include "g" in constructor flags. With global enabled, the engine tracks position via lastIndex and continues searching after each match.

JavaScript
const text = "cat dog cat";

/cat/.exec(text);   // ["cat"] — first only
/cat/g.exec(text); // ["cat"], lastIndex → 3

text.match(/cat/g); // ["cat", "cat"] — all matches

Without g, repeated exec() calls on the same regex keep returning the first match. With g, each call moves forward until no matches remain.

💡
Beginner Tip

To replace every occurrence, always use the global flag: text.replace(/old/g, "new"). A single replace without g changes only the first match.

How to Use the g Modifier

Enable global search on literals, constructors, and combined flags:

JavaScript
/hello/g;                         // global literal
new RegExp("hello", "g");         // constructor
/pattern/gi;                       // global + ignoreCase

re.global;                         // true when g is set
text.matchAll(/\\d+/g);            // requires g (or y with lookahead)
text.replace(/cat/g, "dog");       // replace all

Combine g with other flags like i (case-insensitive) or d (indices). Flag order in the literal does not matter: /cat/gi equals /cat/ig.

📝 Syntax

JavaScript
/pattern/g           // global: all matches
/pattern/gi          // global + ignoreCase
/pattern/gd          // global + indices
new RegExp("p", "g") // constructor
regex.global          // true | false
regex.lastIndex       // search cursor (with g)

Common patterns

  • /pattern/g with match() — array of all matched strings.
  • while ((m = re.exec(s)) !== null) — loop all matches with capture groups.
  • replace(/pat/g, "new") — replace every occurrence.
  • matchAll(/pat/g) — iterator of full match objects.

⚡ Quick Reference

GoalPattern / API
Enable global/pattern/g
Check flagregex.global
All match stringsstr.match(/pat/g)
Loop with groupsexec() + g
Replace allstr.replace(/pat/g, "x")
Iterator of matchesstr.matchAll(/pat/g)

📋 With g vs without g

How the same pattern behaves with and without the global flag.

No g
/cat/

First match only

With g
/cat/g

Every match

match() + g
["cat","cat"]

Strings only

match() no g
["cat"] + index

One result + groups

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover match(), exec loops, replace-all, matchAll, and the global property.

📚 Getting Started

Collect every match with String.match().

Example 1 — match() With and Without g

Global match returns all strings; non-global returns one result.

JavaScript
const text = "cat dog cat bird cat";

console.log(text.match(/cat/g));
// ["cat", "cat", "cat"]

console.log(text.match(/cat/));
// ["cat"] — first only, includes index input
Try It Yourself

How It Works

With g, match() returns a simple array of matched substrings. Without g, you get one match with extra metadata useful for capture groups.

📈 Practical Patterns

Loop, replace, and iterate with the global flag.

Example 2 — Loop All Matches with exec()

Collect every digit sequence using a global regex and a while loop.

JavaScript
const regex = /\d+/g;
const text = "a1 b22 c333";
const found = [];

let match;
while ((match = regex.exec(text)) !== null) {
  found.push(match[0]);
}

console.log(found);          // ["1", "22", "333"]
console.log(regex.lastIndex); // 11 (end of string)
Try It Yourself

How It Works

Each exec() call updates lastIndex. When no more matches exist, exec() returns null. Reset lastIndex = 0 before reusing the regex on the same string.

Example 3 — Replace Every Match with /pattern/g

Swap all occurrences; without g only the first changes.

JavaScript
const text = "cat cat cat";

console.log(text.replace(/cat/g, "pet")); // "pet pet pet"
console.log(text.replace(/cat/, "pet"));  // "pet cat cat"
Try It Yourself

How It Works

The global flag is required for replace-all with replace(). Alternatively, replaceAll() accepts a string or a global regex.

Example 4 — Iterate with matchAll()

Get full match objects (with capture groups) for every date in text.

JavaScript
const text = "2024-01-15 and 2025-07-17";
const re = /(\d{4})-(\d{2})-(\d{2})/g;

for (const m of text.matchAll(re)) {
  console.log(m[0], "year=" + m[1]);
}
// "2024-01-15 year=2024"
// "2025-07-17 year=2025"
Try It Yourself

How It Works

matchAll() requires a global (or sticky) regex. Each yielded value is like an exec() result with groups and index.

Example 5 — Read the global Property

Inspect whether a RegExp was created with the g flag.

JavaScript
const withG = /hello/g;
const withoutG = /hello/;

console.log(withG.global);     // true
console.log(withoutG.global);  // false
console.log(withG.flags);      // "g"
Try It Yourself

How It Works

global is read-only and reflects the flag at creation time. See the global property tutorial for deeper coverage of lastIndex and reuse patterns.

🚀 Common Use Cases

  • Find all occurrences — count how many times a word appears.
  • Replace all — normalize every match in pasted text or logs.
  • Extract all tokens — pull every email, URL, or number from a string.
  • Parse repeated patterns — loop dates or tags with exec() or matchAll().
  • Validation scans — ensure no forbidden substring appears anywhere.
  • Highlight all matches — wrap every search hit in markup for a UI.

Important Considerations

  • Reset lastIndex — reuse of a global regex requires re.lastIndex = 0 before a fresh scan.
  • match() trade-off — global match() drops capture groups from the returned array.
  • Empty matches — patterns like /a*/g can cause infinite loops if lastIndex does not advance; test carefully.
  • Not for test-only checks — use non-global regex when you only need yes/no on first match.
  • Flags are fixed — you cannot toggle g after creation; build a new RegExp instead.

🧠 How the g Modifier Finds All Matches

1

Start at lastIndex

The engine begins searching at lastIndex (0 on first call).

Position
2

Find next match

If a match is found, return it and record the end position.

Match
3

Advance lastIndex

Set lastIndex past the match so the next call continues forward.

Advance
4

Repeat or finish

More text remains → loop again. No match → return null.

📝 Notes

  • g stands for global — search the entire string.
  • matchAll() throws if the regex is not global (unless sticky with appropriate use).
  • Previous modifier: d indices flag.
  • Next modifier: i ignoreCase flag.
  • See also: global property and exec().
  • Combine flags freely: gi, gd, gim, etc.

Browser & Runtime Support

The g global modifier is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp g flag

Supported in every browser and Node.js version. The global flag enables all-match search and replace behavior.

99% Universal syntax
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
g Excellent

Bottom line: Safe everywhere. Use g whenever you need every match, not just the first one.

Conclusion

The g modifier enables global matching—finding, replacing, or iterating every occurrence in a string. It sets global: true, advances lastIndex, and changes what match() returns.

Use /pattern/g for replace-all and matchAll(), loop with exec() when you need capture groups, and reset lastIndex when reusing regex objects. Next, learn the i ignoreCase modifier.

💡 Best Practices

✅ Do

  • Add g when replacing or counting all matches
  • Use matchAll() or exec() loops for groups
  • Reset lastIndex = 0 before re-scanning
  • Check regex.global when debugging behavior
  • Combine with i for case-insensitive global search

❌ Don’t

  • Forget g in replace() when you mean replace-all
  • Expect capture groups from global match()
  • Reuse a global regex without resetting lastIndex
  • Use global regex when only the first match matters
  • Assume you can add g to an existing RegExp object

Key Takeaways

Knowledge Unlocked

Five things to remember about the RegExp g modifier

Find and replace every match in a string, not just the first.

5
Core concepts
📈 02

lastIndex

Cursor.

State
🚫 03

match()

All strings.

API
🔒 04

/pat/g

Replace all.

Replace
🔢 05

matchAll

Iterator.

Groups

❓ Frequently Asked Questions

The g flag (global) tells the engine to find all matches in a string, not just the first one. Methods like exec(), test(), match(), matchAll(), and replace() behave differently when global is enabled.
Append g to the literal: /pattern/g, combine flags like /pattern/gi, or pass 'g' in new RegExp('pattern', 'g'). The global property on the instance becomes true.
With g, match() returns an array of matched strings only—no capture groups in the array. Without g, match() returns one match object (with index and groups) or null.
Without the global flag, exec() always starts from the beginning and returns the first match again. With g, each exec() call advances lastIndex to continue searching.
Yes. string.replace(/pattern/g, replacement) replaces every match. Without g, only the first match is replaced. You can also use string.replaceAll() for string or global-regex patterns.
The global flag is core JavaScript regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

Before matchAll() (ES2020), developers used a while loop with exec() and the g flag to collect every match with capture groups. matchAll() wraps that pattern in a clean iterator—but it still requires the global flag.

Continue to i ignoreCase modifier

Learn how the i flag makes patterns match regardless of letter case.

i modifier tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful