Given this code:
var reg = /a/g;
console.log(reg.test("a"));
console.log(reg.test("a"));
I get this result:
true
false
I have no idea how this could happen. I have tested in both Node.js (v8) and Firefox browser.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To workaround the problem, you can remove the
gflag or resetlastIndexas inThe problem arises because
testis based aroundexecwhich looks for more matches after the first if passed the same string and thegflag is present.The key part of
execis step 6 of 15.10.6.2:When
iis not reset to 0, thenexec(and thereforetest) does not start looking at the beginning of the string.This is useful for
execbecause you can loop to handle each match:but obviously it isn’t so useful for
test.