JavaScript RegExp g Flag

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is the g Flag?

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

Remember
/pattern/g          // enable global
regex.global        // true when g is set
regex.lastIndex     // search cursor (advances with g)

match()  + g  → all matched strings
replace() + g → replace every match
exec()   + g  → next match each call
UsePrefer
All match stringsstr.match(/pat/g)
Replace every hitstr.replace(/pat/g, "x")
Groups for every hitstr.matchAll(/pat/g) or exec loop

How to Use the g Flag

Add g, then choose the method that fits your goal.

  1. Create a global regex: /pattern/g or new RegExp("pattern", "g").
  2. Use match for a simple list of strings, or replace to change every hit.
  3. Use matchAll or an exec loop when you need capture groups / index for each match.
  4. Before reusing the same global regex on a fresh scan, set re.lastIndex = 0.
PieceRequired?Role
g flagYesSearch the whole string for all matches
lastIndexAutoCursor advanced by exec / test when global
Other flagsOptionale.g. gi, gd with i / d

Pseudocode

Pseudocode
re = /pattern/g
re.lastIndex = 0

loop:
    m = re.exec(text)
    if m is null:
        stop
    else:
        use m[0], m.index, groups…
        // lastIndex already moved past this match

Cheat Sheet

Keep these global-flag facts handy.

TopicDetail
Syntax/pattern/g or new RegExp(p, "g")
Check flagregex.global
match + gArray of strings (no groups in result)
match without gOne match object (or null)
replace + gReplace every match
matchAllRequires global regex; yields full match objects
lastIndexReset to 0 before a fresh scan
StandardES3+ (universal)

Live Preview

Compare global vs non-global behavior on "cat dog cat bird cat".

Browser demo of the global flag — same idea as the examples below.

Result
text.match(/cat/g)
→ ["cat", "cat", "cat"]

/* g finds every "cat" */

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — match() With and Without g

Global match returns every string; without g you get one match object.

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

console.log(text.match(/cat/g));  // ["cat", "cat", "cat"]
console.log(text.match(/cat/));   // ["cat", index: 0, …]

console.log(/cat/g.global);       // true
console.log(/cat/.global);        // false
Try It Yourself

How It Works

  1. Add g. /cat/g sets global to true.
  2. Collect every string. Global match returns ["cat", "cat", "cat"].
  3. Without g. You get one match object with index (and groups if any).
  4. Trade-off. Global match does not include capture groups in the returned array — use matchAll or exec when you need them.

Example 2 — Replace Every Match

Use replace with g to change all hits; 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

  1. Global replace. /cat/g finds every "cat" and swaps it for "pet".
  2. Non-global replace. Without g, only the first match is replaced.
  3. Original unchanged. Strings are immutable — both calls return new strings.
  4. Alternative. replaceAll also works; with a RegExp it still requires the global flag.

Example 3 — exec() Loop and lastIndex

Walk every match with a global regex; each exec advances the search cursor.

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

while ((m = re.exec(text)) !== null) {
  found.push(m[0]);
}

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

How It Works

  1. Start at lastIndex 0. The first exec finds "1".
  2. Advance the cursor. After each hit, lastIndex moves past that match.
  3. Continue until null. When nothing is left, exec returns null and the loop stops.
  4. Reuse carefully. Set re.lastIndex = 0 before scanning the same regex again from the start.

Edge Cases & Pitfalls

Check these before relying on the global flag.

lastIndex

Reset before reusing

A leftover lastIndex can skip matches. Set re.lastIndex = 0 for a fresh scan (see also global).

match

Global match drops groups

With g, match returns strings only. Need captures? Use matchAll or an exec loop.

test

test() also advances lastIndex

Repeated test calls on a global regex can alternate true/false. Prefer a non-global regex for simple yes/no checks.

empty

Zero-length matches

Patterns like /a*/g can match empty strings. Ensure lastIndex advances, or you risk an infinite loop.

Browser & Runtime Support

The g (global) flag is part of core JavaScript regular expression syntax (ES3+).

✓ Baseline · ES3+

RegExp g / global

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 flag Excellent

Bottom line: Safe everywhere. Use g whenever you need every match — and remember lastIndex when reusing the same RegExp instance.

Performance Notes

ApproachCostBest for
match(/…/g)O(n)Simple list of all match strings
replace(/…/g, …)O(n)Replace every occurrence
matchAll / exec loopO(n)All matches with groups / index

Global search still walks the string once. Prefer match for plain strings; use matchAll or exec when you need capture details. Avoid restarting from scratch for each hit.

Key Takeaways

  • Role: g finds every match, not just the first.
  • Replace all: always use /pattern/g with replace.
  • Cursor: lastIndex advances — reset it before reuse.
  • Groups: prefer matchAll / exec over global match.

One line: add g when you need every match — and respect lastIndex when you reuse the regex.

Frequently Asked Questions

The g flag (global) tells the engine to find all matches in a string, not just the first one. Methods like match(), exec(), test(), 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'). Then regex.global is true.
With g, match() returns an array of matched strings only—no capture groups in that array. Without g, match() returns one match object (with index and groups) or null.
With g, each exec() call advances lastIndex so the next call continues forward. Without g, exec() always starts from the beginning and returns the first match again.
Yes for replace(): string.replace(/pattern/g, replacement) replaces every match. Without g, only the first match changes. replaceAll() also requires a global regex when you pass a RegExp.
The global flag is core JavaScript regex syntax since ES3. It works in every browser and Node.js version.

Next: i modifier

Learn case-insensitive matching with the i flag.

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.

12 people found this page helpful