lastIndex is a read/write integer property of regular expression instances that specifies the index at which to start the next match.

特性属性在 RegExpInstance.lastIndex
可写 yes
可枚举 no
可配置 no

描述

This property is set only if the regular expression instance used the g flag to indicate a global search, or the y flag to indicate a sticky search. The following rules apply:

  • lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.
  • lastIndex is equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from lastIndex .
  • lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
  • Otherwise, lastIndex is set to the next position following the most recent match.

范例

Using lastIndex

Consider the following sequence of statements:

var re = /(hi)?/g;
					

Matches the empty string.

console.log(re.exec('hi'));
console.log(re.lastIndex);
					

返回 ["hi", "hi"] with lastIndex equal to 2.

console.log(re.exec('hi'));
console.log(re.lastIndex);
					

返回 ["", undefined] , an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex was 2 (and still is 2) and hi has length 2.

规范

规范
ECMAScript (ECMA-262)
The definition of 'RegExp.lastIndex' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
lastIndex Chrome 1 Edge 12 Firefox 1 IE 5.5 Opera 5 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: