javascript - Why does the "g" modifier give different results when test() is called twice? -
javascript - Why does the "g" modifier give different results when test() is called twice? -
given code:
var reg = /a/g; console.log(reg.test("a")); console.log(reg.test("a")); i result:
true false i have no thought how happen. have tested in both node.js (v8) , firefox browser.
to workaround problem, can remove g flag or reset lastindex in
var reg = /a/g; console.log(reg.test("a")); reg.lastindex = 0; console.log(reg.test("a")); the problem arises because test based around exec looks more matches after first if passed same string , g flag present.
15.10.6.3 regexp.prototype.test(string) # Ⓣ Ⓡ
the next steps taken:
let match result of evaluatingregexp.prototype.exec (15.10.6.2) algorithm upon regexp object using string argument. if match not null, homecoming true; else homecoming false. the key part of exec step 6 of 15.10.6.2:
6. allow global result of calling [[get]] internal method of r argument "global". 7. if global false, allow = 0.
when i not reset 0, exec (and hence test) not start looking @ origin of string.
this useful exec because can loop handle each match:
var myregex = /o/g; var mystring = "fooo"; (var match; match = myregex.exec(mystring);) { alert(match + " @ " + myregex.lastindex); } but isn't useful test.
javascript regex
Comments
Post a Comment