[thelist] Javascript regex lastindex property with global flag on [TIP]
VOLKAN ÖZÇELİK
volkan.ozcelik at gmail.com
Tue Aug 30 14:03:49 CDT 2005
Hope there isn't some flaw in my reasoning as it was in my previous tip.
Cheers,
Volkan.
<tip author="Volkan Ozcelik" type="JavaScript (regular expressions)">
if you are using the global flag (g) in a regular expression, make
sure you reset the lastIndex property before you do any test or match.
Otherwise the match will begin from the lastIndex of the test string.
A sample may be more explanatory::
script1.js
-------------
var re=/foobar/ig;
var str="foobar bazobar";
alert(re.lastIndex);//returns 0
alert(re.test(str));//returns true
alert(re.lastIndex);//returns 6
alert(re.test(str));//returns false !
script2.js
-------------
var re=/foobar/ig;
var str="foobar bazobar";
alert(re.lastIndex);//returns 0
alert(re.test(str));//returns true
re.lastIndex=0;//note that we set last index to zero before the next test.
alert(re.lastIndex);//returns 0
alert(re.test(str));//returns true !
</tip>
More information about the thelist
mailing list