RegExp.prototype.hasIndices

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上运行。自 2021 年 9 月起,所有浏览器均已支持此功能。

hasIndices 访问器属性是 RegExp 实例的一个属性,用于指示此正则表达式是否使用了 d 标志。

试一试

const regex1 = /foo/d;

console.log(regex1.hasIndices);
// Expected output: true

const regex2 = /bar/;

console.log(regex2.hasIndices);
// Expected output: false

描述

如果使用了 d 标志,则 RegExp.prototype.hasIndices 的值为 true;否则为 falsed 标志表示正则表达式匹配的结果应包含每个捕获组的子字符串的起始和结束索引。它不会以任何方式改变正则表达式的解释或匹配行为,仅在匹配结果中提供额外信息。

此标志主要影响 exec() 的返回值。如果存在 d 标志,则 exec() 返回的数组将具有一个附加的 indices 属性,具体描述参见 exec() 方法的 返回值。由于所有其他与正则表达式相关的方法(例如 String.prototype.match())在内部都会调用 exec(),因此如果正则表达式带有 d 标志,它们也将返回索引。

hasIndices 的 set 访问器为 undefined。您无法直接更改此属性。

示例

分组和反向引用 > 使用分组和匹配索引 中有更详细的用法示例。

使用 hasIndices

js
const str1 = "foo bar foo";

const regex1 = /foo/dg;

console.log(regex1.hasIndices); // true

console.log(regex1.exec(str1).indices[0]); // [0, 3]
console.log(regex1.exec(str1).indices[0]); // [8, 11]

const str2 = "foo bar foo";

const regex2 = /foo/;

console.log(regex2.hasIndices); // false

console.log(regex2.exec(str2).indices); // undefined

规范

规范
ECMAScript® 2026 语言规范
# sec-get-regexp.prototype.hasIndices

浏览器兼容性

另见