Bug with RegExp in JavaScript when do global search

javascript, regex

Solution

The reason for this behavior is that RegEx isn't stateless. Your second `test` will 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, as `lastIndex` is reset when no match is found:

var pattern = /te/gi;

pattern.test('test');
>> true
pattern.lastIndex;
>> 2

pattern.test('test');
>> false
pattern.lastIndex;
>> 0

You'll notice how this changes when there are two matches, for instance:

var pattern = /t/gi;

pattern.test('test');
>> true
pattern.lastIndex;
>> 1

pattern.test('test');
>> true
pattern.lastIndex;
>> 4

pattern.test('test');
>> false
pattern.lastIndex;
>> 0

Problem

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?

Original source

Related problems