RegExp Named Groups Drive exec Loops
Iterate global regexes with a while-exec loop typed as RegExpExecArray | null, reading named groups and tracking lastIndex across matches.
Code
// Named groups make exec results self-describing; exec drives the loop
const record = /(?<key>[a-z]+)=(?<value>\d+)/g;
const input = 'color=3 frame=60 level=12';
// RegExpExecArray | null is the loop type: every access is guarded
let match: RegExpExecArray | null = record.exec(input);
const settings: Array<{ key: string; value: number }> = [];
while (match !== null) {
settings.push({
key: match.groups?.key ?? 'unknown',
value: Number(match[2]),
});
console.log('consumed up to:', record.lastIndex);
match = record.exec(input);
}
console.log(settings);
// The terminating call returns null and resets lastIndex to 0
console.log('final exec:', match, 'lastIndex reset to:', record.lastIndex);
// Calling exec again restarts the scan from index 0: fresh pass, fresh match
console.log('restart exec:', record.exec(input), 'lastIndex:', record.lastIndex);What the code does
The loop while (match !== null) is the only repeated construct.
The whole flow works on the top-level bindings: record, input, match.
What to watch for
- No dependencies section needed; the standard library is the whole story.
Using it
The run prints consumed up to: after each match, then closes with final exec: showing the terminating null and restart exec: re-matching from index 0.
Key statements
while (match !== null) {
settings.push({
key: match.groups?.key ?? 'unknown',
value: Number(match[2]),
});
console.log('consumed up to:', record.lastIndex);
match = record.exec(input);
}
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
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `record`, `input`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.