The result of the following code execution is false. Why?

interview related

related codes

var re = /abc/g;
console.log(re.test("abcd")===re.test("abcd")); // false
Jul.13,2022
The g in the

regular expression, so that after the search process, if the match is successful, the last position will be recorded, and if the match is not successful, it will return to zero, so the first time is true, the second time is false, and the judgment result is false


.
test () called multiple times on the same global regular expression instance will advance past the previous match

because the regularities in the example come with g, each call to the test method fetches a hidden property lastIndex, skipping the part that was searched last time. The next time it is called, the search starts with the previous lastIndex. If you can't find it, return false. LastIndex is set to 0, and the next call will find

again.

execute the following statement several times to make it clear

   

there are two executions here, lastIndex is different

Menu