SoFunction
Updated on 2025-03-02

A question about Javascript lastIndex regular expressions

Look at the following code:
function test(s){
var reg = /./g;
((s));
();
var reg = /./g;
((s));
();
}
test("abcd");
test("efgh");
I thought the output lastIndex value should be 1, but the actual output is as follows:
a
1
a
1
f
2
f
2
It feels like lines 2 and 6 do not produce new regular expressions when the test is called the second time, and its previous attribute lastIndex is still retained (lastIndex=1). This is a bit unreasonable and has a headache. . . . . .