JS: Regex Flag d (hasIndices)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2022)

What is regex flag d

The regex flag d adds start and end positions of the matched string and captures, in the regex result array, in the property indices.

// with flag d
// you get a new property named indices in the result.
console.log(
 /i/d.exec("Alice was"),
);

/*
[
  "i",
  index: 2,
  input: "Alice was",
  groups: undefined,
  indices: [ [ 2, 3 ], groups: undefined ]
]
*/

// s------------------------------

// without flag d
console.log(
 /i/.exec("Alice was"),
);
// [ "i", index: 2, input: "Alice was", groups: undefined ]

Example. show indices of matched string with capture

// with flag d
const xresult = /(.)\d+/d.exec("a1498 b9433");

console.log(xresult);
/*
[
  "a1498",
  "a",
  index: 0,
  input: "a1498 b9433",
  groups: undefined,
  indices: [ [ 0, 5 ], [ 0, 1 ], groups: undefined ]
]
*/

// the match string
console.log(xresult[0]);
// a1498

// the captured substring
console.log(xresult[1]);
// a

// the property indices added by flag d
console.log(xresult.indices);
// [ [ 0, 5 ], [ 0, 1 ], groups: undefined ]

// the start/end positions of matched string
console.log(xresult.indices[0]);
// [ 0, 5 ]

// the start/end positions of first captured substring
console.log(xresult.indices[1]);
// [ 0, 1 ]

Regexp.prototype.hasIndices

RegExp.prototype.hasIndices is a Getter Property. Value is true if flag d is set, on the given regex object.

const x = /i/d;
console.assert(x.hasIndices === true);