RegExpInstance.lastIndex - JavaScript 编辑

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

Property attributes of RegExpInstance.lastIndex
Writableyes
Enumerableno
Configurableno

Description

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:

  • If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.
  • If 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.
  • If 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.

Examples

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);

Returns ["hi", "hi"] with lastIndex equal to 2.

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

Returns ["", 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.

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:58 次

字数:4672

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文