6

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?

Community
  • 1
  • 1

4 Answers4

12

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
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

I suppose you ran into this problem: https://bugzilla.mozilla.org/show_bug.cgi?id=237111

Removing the g parameter solves the issue. Basically its due to the lastindex property that remember last value every time you execute test() method

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

To quote the MDN Docs (emphasis mine):

When you want to know whether a pattern is found in a string use the test method (similar to the String.search method); for more information (but slower execution) use the exec method (similar to the String.match method). As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

This is the intended behavior of the RegExp.test(str) method. The regex instance (pattern) stores state which can be seen in the lastIndex property; each time you call "test" it updates that value and following calls with the same argument may or may not yield the same result:

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".
maerics
  • 151,642
  • 46
  • 269
  • 291