Discuss in detail the impact of lastIndex on regular results

小云云
Release: 2023-03-17 20:00:02
Original
1574 people have browsed it

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
Copy after login


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
Copy after login


After the first successful match using test(), lastIndex is Set to the end position of matching, which is 1; when test() is performed for the second time, matching starts from index 1. If the matching fails, 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
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!