Error with RegExp in JavaScript in global search

Possible duplicate:
Javascript regex returns true .. then false .. then true .. etc.

First of all, I apologize for my poor English.

I am trying to check a string against a pattern, so I 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 such unexpected results:

>>> pattern.test(str)
true
>>> pattern.test(str)
false
>>> pattern.test(str)
true

Can anyone explain this?

+5
source share
4 answers

The reason for this behavior is that RegEx is not stateless. Your second testwill continue to search for the next match in the string and tells you that he no longer finds it. Further searches begin from the beginning, as lastIndex- reset when no match is found:

var pattern = /te/gi;

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

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

, , , :

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
+10
+2

MDN Docs ( ):

, , ( String.search); ( ) exec ( String.match). exec ( ), , , .

+1

RegExp.test(str). () , lastIndex; , "", , :

var str="test", pattern=new RegExp("te", "gi");
pattern.lastIndex; // => 0, since it hasn't found any matches yet.
pattern.test(str); // => true, since it matches at position "0".
pattern.lastIndex; // => 2, since the last match ended at position "1".
pattern.test(str); // => false, since there is no match after position "2".
0

All Articles