--- title: RegExp.lastIndex slug: Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex tags: - JavaScript - Property - Reference - RegExp - Regular Expression translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex ---
lastIndex
は正規表現インスタンスの読み書き可能なプロパティで、次の一致を開始する位置を指定します。
regExpObj.lastIndex
このプロパティは、正規表現インスタンスがグローバル検索を示すために g
フラグを使用した場合、または粘着的検索を示すために y
フラグを使用した場合にのみ設定されます。以下の規則が適用されます。
lastIndex
が文字列の長さよりも大きければ、 {{jsxref("RegExp.prototype.test()", "test()")}} および {{jsxref("RegExp.prototype.exec()", "exec()")}} は失敗し、lastIndex
は 0 にセットされます。lastIndex
が文字列の長さ以下で、かつ正規表現が空文字列に一致する場合には、正規表現は lastIndex
から始まる入力に一致します。lastIndex
が文字列の長さと等しく、かつ、正規表現が空文字列に一致しない場合、正規表現は入力に一致せず、 lastIndex
は 0 にリセットされます。lastIndex
は直近の一致に続く次の位置に設定されます。例えば、以下の連続した処理を考えてみてください。:
var re = /(hi)?/g;
空文字列に一致します。
console.log(re.exec('hi')); console.log(re.lastIndex);
lastIndex
が 2 になり["hi", "hi"]
が返ります。
console.log(re.exec('hi')); console.log(re.lastIndex);
ゼロ番目の要素が一致した文字列なので、 ["", undefined]
という空配列が返ります。この場合、 lastIndex
が 2 であったときに (そして 2 のままである)、 hi
の長さが 2 であるので、空文字列になります。
仕様書 |
---|
{{SpecName('ESDraft', '#sec-properties-of-regexp-instances', 'RegExp.lastIndex')}} |
{{Compat("javascript.builtins.RegExp.lastIndex")}}