RegExp.prototype.hasIndices

hasIndicesRegExp インスタンスのプロパティで、その正規表現で d フラグが使用されたかどうかを示します。

試してみましょう

解説

RegExp.prototype.hasIndices の値は d フラグが使用されている場合に true となり、そうでない場合は false となります。d フラグは、正規表現の照合結果に各キャプチャグループの部分文字列の開始と終了のインデックスを含めることを示します。これは正規表現の解釈や照合の動作を変更するものではなく、照合結果に追加情報を与えるだけです。

このフラグは、主に exec() の返値に影響します。d フラグが存在する場合、exec() によって返される配列は、exec() メソッドの返値に記述されているように、追加の indices プロパティを持ちます。他のすべての正規表現関連のメソッド(String.prototype.match() など)は、内部的に exec() を呼び出すので、正規表現に d フラグがある場合、インデックスも返します。

hasIndices の設定アクセサーは 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

仕様書

Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.hasIndices

ブラウザーの互換性

BCD tables only load in the browser

関連情報