--- title: RegExp.lastIndex slug: Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex tags: - JavaScript - Property - RegExp - Regular Expressions translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex ---
lastIndex 是正则表达式的一个可读可写的整型属性,用来指定下一次匹配的起始索引。
lastIndex = regExpObj.lastIndex;
只有正则表达式使用了表示全局检索的 "g" 标志时,该属性才会起作用。此时应用下面的规则:
lastIndex 大于字符串的长度,则 regexp.test 和 regexp.exec 将会匹配失败,然后 lastIndex 被设置为 0。lastIndex 等于字符串的长度,且该正则表达式匹配空字符串,则该正则表达式匹配从 lastIndex 开始的字符串。(then the regular expression matches input starting at lastIndex.)lastIndex 等于字符串的长度,且该正则表达式不匹配空字符串 ,则该正则表达式不匹配字符串,lastIndex 被设置为 0.。lastIndex 被设置为紧随最近一次成功匹配的下一个位置。考虑下面的语句:
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. |
| {{SpecName('ES5.1', '#sec-15.10.7.5', 'RegExp.lastIndex')}} | {{Spec2('ES5.1')}} | |
| {{SpecName('ES6', '#sec-properties-of-regexp-instances', 'RegExp.lastIndex')}} | {{Spec2('ES6')}} |