試一試
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;否則為 false。d 標誌表示正則表示式匹配的結果應包含每個捕獲組的子字串的起始和結束索引。它不會以任何方式改變正則表示式的解釋或匹配行為,僅在匹配結果中提供額外資訊。
此標誌主要影響 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 |
瀏覽器相容性
載入中…