非常教程

JavaScript参考手册

RegExp

regExp.lastIndex

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

| RegExp.lastIndex属性的属性特性 |

|:----|

| Writable | yes |

| Enumerable | no |

| Configurable | no |

语法

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 被设置为紧随最近一次成功匹配的下一个位置。

示例

使用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 (ECMA-262)

Standard

Initial definition. Implemented in JavaScript 1.2. JavaScript 1.5: lastIndex is a property of a RegExp instance, not the RegExp object.

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

Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.lastIndex' in that specification.

Standard

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

Draft

浏览器兼容性

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)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络