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.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// 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

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`.