概述

lastIndex 是正则表达式的一个可读可写的整型属性,用来指定下一次匹配的起始索引。

RegExp.lastIndex 属性的属性特性:
writable true
enumerable false
configurable false

语法

lastIndex = regExpObj.lastIndex;

描述

只有正则表达式使用了表示全局检索的 "g" 标志时,该属性才会起作用。此时应用下面的规则:

示例

考虑下面的语句:

var re = /(hi)?/g;
 

匹配空字符串

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

返回 ["hi", "hi"] ,lastIndex 等于 2。

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

返回 ["", undefined],即一个数组,其第 0 个元素为匹配的字符串。此种情况下为空字符串,是因为 lastIndex 为 2(且一直是 2),"hi" 长度为 2。

规范

Specification Status Comment
ECMAScript 3rd Edition. Implemented in JavaScript 1.2. Standard Initial definition.
JavaScript 1.5: lastIndex is a property of a RegExp instance, not the RegExp object.
ECMAScript 5.1 (ECMA-262)
RegExp.lastIndex
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
RegExp.lastIndex
Standard  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

相关链接