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 global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.
For a global, case-insensitive search, use the "i" modifier together with the g modifier.
In case you are wondering which one will perform better if the string is too big, 'regex. test' is the fastest, followed by 'string.search' from ES6 libraries, and the third place belongs to string.
A regular expression consists of a pattern and optional flags: g , i , m , u , s , y . Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. The method str. match(regexp) looks for matches: all of them if there's g flag, otherwise, only the first one.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With