Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

JavaScript RegExp `d` Flag: Get Match Indices

1 min read .
JavaScript RegExp `d` Flag: Get Match Indices

The JavaScript regular-expression d flag enables match indices. It does not collect repeated captures; instead, it adds an indices property that tells you the start and end offsets of the overall match and each capturing group.

Basic Example

const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/d;
const match = regex.exec('Date: 2024-08-30');

console.log(match[0]);                 // 2024-08-30
console.log(match.indices[0]);         // [6, 16]
console.log(match.indices.groups.year);  // [6, 10]
console.log(match.indices.groups.month); // [11, 13]
console.log(match.indices.groups.day);   // [14, 16]

The end index is exclusive, matching the behavior of String.prototype.slice().

Extract the Exact Source Slice

const [start, end] = match.indices.groups.month;
console.log('Date: 2024-08-30'.slice(start, end)); // 08

This is useful for syntax highlighting, editor tooling, parsers, validation messages, and diagnostics where the position of a match matters.

Find Multiple Matches

Combine d with g and matchAll() when you need indices for every occurrence:

const text = '2024-08-30 and 2023-12-25';
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/dg;

for (const match of text.matchAll(regex)) {
  console.log(match[0], match.indices[0]);
}

Each match has its own capture values and index ranges.

Conclusion

Use the d flag when you need the positions of RegExp matches and capturing groups. For repeated matches, combine it with g and matchAll() rather than expecting one match object to collect every occurrence.

Related Posts

chevron-up