Home  >  Article  >  Web Front-end  >  The relationship between lastIndex and regular expressions

The relationship between lastIndex and regular expressions

php中世界最好的语言
php中世界最好的语言Original
2018-03-29 11:02:351787browse

This time I will bring you the relationship between lastIndex and regular expressions. What are the notes when using lastIndex and regular expressions? The following is a practical case. Let’s take a look. .

Preface

I encountered a problem today. When using regular expressions to check the same string, alternate Returns true and false. In desperation, I looked through the authoritative guide again and found that the culprit turned out to be lastIndex. You can try it in the console

let reg = /[\d]/g
//undefined
reg.test(1)
//true
reg.test(1)
//false

lastIndex

lastIndex is explained as follows in the authoritative guide: It is a read/writeInteger. If the matching pattern has the g modifier, this attribute is stored at the beginning of the next index in the entire string. This attribute will be used by exec() and test(). Still using the above example, observe the lastIndex attribute

let reg = /[\d]/g  //有修饰符g
//undefined
reg.lastIndex
//0
reg.test(1)   
//true
reg.lastIndex  //匹配一次后,lastIndex改变
//1
reg.test(1)  //从index 1 开始匹配
//false
reg.lastIndex
//0
reg.test(1)
//true
reg.lastIndex
//1

After the first successful match using test(), lastIndex is set to the end position of the match, which is 1; when testing() is used for the second time, from Matching starts at index 1, the match fails, and lastIndex is reset to 0. This causes the matching results to be inconsistent with expectations

Solution

1. Do not use the g modifier

reg = /[\d]/
///[\d]/
reg.test(1)
//true
reg.test(1)
//true
reg.lastIndex
//0
reg.test(1)
//true
reg.lastIndex

2. Manually set lastIndex = 0 after test()

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the use of the \D metacharacter (equivalent to "[^0-9]") in regular expressions

Organization of commonly used regular expressions

The above is the detailed content of The relationship between lastIndex and regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn