Home >Backend Development >PHP Tutorial >Discuss in detail the impact of lastIndex on regular results
When using regular expressions to check the same string, true and false are returned alternately. In desperation, I looked through the authoritative guide again and found that the culprit turned out to be lastIndex. This article will share with you the impact of lastIndex on regular results.
let reg = /[\d]/g //undefined reg.test(1) //true reg.test(1) //false
lastIndex
lastIndex is explained as follows in The Definitive Guide: It is a readable/ written integer. 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
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()
The above content is the lastIndex pair The impact of regular results, I hope it can help everyone. Related recommendations:Detailed explanation of the use of lastIndexOf() method for arrays and strings in JavaScript_Basic knowledge
Usage of indexOf and lastIndexOf Example introduction_javascript skills
js lastIndexOf() usage example
The above is the detailed content of Discuss in detail the impact of lastIndex on regular results. For more information, please follow other related articles on the PHP Chinese website!