RegExp hasIndices d Flag Reports Match Spans
Enable the d flag on regular expressions so every match exposes start and end indices for the whole pattern and each capture group.
Code
// d flag (hasIndices): match.indices records spans
const pattern = /(\d{4})-(\d{2})-(\d{2})/d;
const match = pattern.exec('released 2026-11-17');
if (match) {
console.log('full:', match[0]);
console.log('indices:', match.indices[0]);
for (let i = 1; i < match.length; i += 1) {
const [start, end] = match.indices[i];
console.log('group', i, '->', match[0].slice(start - match.index, end - match.index));
}
}
// 命名分组同样记录区间
const named = /(?<year>\d{4})-(?<month>\d{2})/d.exec('2026-11');
console.log('year range:', named.indices.groups.year);
console.log('month text:', named.groups.month);
// 没有 d 标志时 indices 为 undefined
const plain = /x/.exec('x');
console.log('plain has indices:', plain.indices !== undefined);How the snippet works
Iteration happens inside for (let i = 1; i < match.length; i += 1) — everything outside it runs once.
Demo state sits in top-level bindings: pattern, match, named, plain.
Applying it
The run emits 6 labeled sections — full:, indices:, group, year range:, month text:, plain has indices: — one per step.
Statements that matter
const match = pattern.exec('released 2026-11-17');
for (let i = 1; i < match.length; i += 1) {
const [start, end] = match.indices[i];
console.log('group', i, '->', match[0].slice(start - match.index, end - match.index));
}
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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.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.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `pattern`, `match`, `named`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.