Possible Duplicate:
Javascript regex returning true.. then false.. then true.. etc
First of all, apologize for my bad english.
I’m trying to test string to match the pattern, so I has wrote this:
var str = 'test';
var pattern = new RegExp('te', 'gi'); // yes, I know that simple 'i' will be good for this
But I have this unexpected results:
>>> pattern.test(str)
true
>>> pattern.test(str)
false
>>> pattern.test(str)
true
Can anyone explain this?
The reason for this behavior is that RegEx isn’t stateless. Your second
testwill continue to look for the next match in the string, and reports that it doesn’t find any more. Further searches starts from the beginning, aslastIndexis reset when no match is found:You’ll notice how this changes when there are two matches, for instance: