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.
Code
// 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: 0The 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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.