Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug with RegExp in JavaScript when do global search [duplicate]

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?

like image 350
George Vinogradov Avatar asked Apr 19 '12 13:04

George Vinogradov


People also ask

What does global do in regex?

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.

What function perform case insensitive and global searches in RegExp?

For a global, case-insensitive search, use the "i" modifier together with the g modifier.

Is regex faster JavaScript?

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.

What is pattern flags in regex?

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.


1 Answers

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
like image 164
David Hedlund Avatar answered Sep 21 '22 01:09

David Hedlund