The Solution of Regular test of Incorrect Repeated Execution Caused by Misuse of and g in JavaScript

  • 2021-07-06 09:53:43
  • OfStack

1 simple use of regularity to determine whether the input is a number:


input1 = '0281234567';input2 = '0282345678';var reg = /^\d+$/g;
reg.test(input1); //true
reg.test(input2); //false 

Found that the second test returned the wrong value. After eliminating various interference factors such as writing errors, value failure, etc., it was found that only when reg was executed the second time, it could not be executed correctly. I didn't encounter this problem before, so I searched for relevant information for 1 time.

It turns out that this problem is actually caused by/g. At this time, it was discovered that in fact, I misused the/g for this regularity. Because the/g represents a global match, there is an lastIndex inside to record the last matching position when judging regularity. When calling repeatedly, it will continue to match with the last lastIndex, which will lead to an error in judgment. Understand the principle and solve it very clearly:

1. Remove the/g, and do not add the/g logo at will when the/g is not needed

2. Before the second match, set lastIndex to 0 manually, as in the above example: reg. lastIndex () = 0.


Related articles: