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.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Property attributes of RegExpInstance.lastIndex | |
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
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()
andexec()
fail, thenlastIndex
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 fromlastIndex
. - 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, andlastIndex
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论