matchAll Requires The Global Flag

matchAll throws TypeError without the /g flag because a non-global regex would match forever; it iterates a clone, so the original lastIndex stays untouched.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
// matchAll requires the /g flag: a non-global regex would match the first
// position forever, so the engine refuses up front with a TypeError.
try {
  'a1b2'.matchAll(/\d/);
} catch (error) {
  console.log('without /g:', error.constructor.name);
}

const pattern = /\d/g;
const found = [...'a1b2c3'.matchAll(pattern)];
console.log('with /g:', found.map((m) => m[0]).join(','));

// matchAll iterates a clone: the original regex lastIndex stays 0, while
// an exec loop advances it and must be reset between inputs.
console.log('original lastIndex after matchAll:', pattern.lastIndex);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

without /g: TypeError
with /g: 1,2,3
original lastIndex after matchAll: 0

The mechanics of this demo — matchAll Requires The Global Flag

Demo state sits in top-level bindings: pattern, found.

Watch out for

  • No package installation, no environment variables, no setup steps.

Using it

The file’s steps show up in the output as without /g:, with /g:, original lastIndex after matchAll:.

Key statements

const found = [...'a1b2c3'.matchAll(pattern)];
'a1b2'.matchAll(/\d/);
const pattern = /\d/g;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `pattern`, `found`.