--- 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 ---
{{JSRef}}

lastIndex は正規表現インスタンスの読み書き可能なプロパティで、次の一致を開始する位置を指定します。

{{EmbedInteractiveExample("pages/js/regexp-lastindex.html")}}
{{js_property_attributes(1, 0, 0)}}

構文

regExpObj.lastIndex

解説

このプロパティは、正規表現インスタンスがグローバル検索を示すために g フラグを使用した場合、または粘着的検索を示すために y フラグを使用した場合にのみ設定されます。以下の規則が適用されます。

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")}}

関連情報