このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
RegExp.prototype.hasIndices
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2021年9月.
hasIndices はRegExp インスタンスのプロパティで、その正規表現でd フラグが使用されたかどうかを示します。
In this article
試してみましょう
const regex1 = /foo/d;console.log(regex1.hasIndices);// 予想される結果: trueconst regex2 = /bar/;console.log(regex2.hasIndices);// 予想される結果: false解説
RegExp.prototype.hasIndices の値はd フラグが使用されている場合にtrue となり、そうでない場合はfalse となります。d フラグは、正規表現の照合結果に各キャプチャグループの部分文字列の開始と終了のインデックスを含めることを示します。これは正規表現の解釈や照合の動作を変更するものではなく、照合結果に追加情報を与えるだけです。
このフラグは、主にexec() の返値に影響します。d フラグが存在する場合、exec() によって返される配列は、exec() メソッドの返値に記述されているように、追加のindices プロパティを持ちます。他のすべての正規表現関連のメソッド(String.prototype.match() など)は、内部的にexec() を呼び出すので、正規表現にd フラグがある場合、インデックスも返します。
hasIndices の設定アクセサーはundefined です。このプロパティを直接変更することはできません。
例
グループと後方参照 > グループと一致結果の添字の使用に詳しい使用例があります。
hasIndices の使用
const str1 = "foo bar foo";const regex1 = /foo/dg;console.log(regex1.hasIndices); // trueconsole.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); // falseconsole.log(regex2.exec(str2).indices); // undefined仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-get-regexp.prototype.hasIndices> |