regex - Javascript RegExp Producing Unusual Results with Global Modifer -
this question has answer here:
i able work around issue turned out didn't need /g. wondering if able explain why following behavior occurred.
x = regexp( "w", "gi" ) x.test( "women" ) = true x.test( "women" ) = false
it continue alternate between true , false when evaluating expression. issue because using same compiled regexp on list of strings, leading evaluate false when should have been true.
when use g
flag, regex stores end position of match in lastindex
property. next time call of test()
, exec()
, or match()
, regex start index in string try , find match.
when no match found, return null, , lastindex
reset 0. why test kept alternating. match w
, , lastindex
set 1. next time called it, null returned, , lastindex
reset.
a pitfall related when regex can match empty string. in case, lastindex
not change, , if getting matches, there infinite loop. in case should manually adjust lastindex
if matched empty string.
Comments
Post a Comment