Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "g" in RegExp test method works alternatively?

http://jsfiddle.net/bpt33/

var t = "";

var a = ["atom-required","atom-label","atom-data-type","atom-regex"];

var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/i;

function test(a, r){
    for(var i = 0; i<a.length; i++){
        t += a[i] + " => " + r.test(a[i]) + "<br/>";
    }
}

test(a, r);

t += "<br/>";

a = ["atom-required","atom-label","atom-data-type","atom-regex"];

var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/gi;

test(a, r);

$("#results").get(0).innerHTML = t;

When g is not specified, it works correctly,

atom-required => true
atom-label => true
atom-data-type => true
atom-regex => true

When g is specified, it works alternatively

atom-required => true
atom-label => false
atom-data-type => true
atom-regex => false
like image 618
Akash Kava Avatar asked Jun 09 '13 20:06

Akash Kava


People also ask

What does G in regex do?

The g flag indicates that the regular expression should be tested against all possible matches in a string.

What is G in JS regex?

Definition and Usage The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

How does regex test work?

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false . JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y ). They store a lastIndex from the previous match.

What can be matched using (*) in a regular expression?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.


1 Answers

Because with the g modifier, the regexp becomes stateful, and resumes the next search at the index after the last match.

When no match is found, it resets itself.

You can observe the starting point by using the .lastIndex property.

r.lastIndex; // 0 or some higher index

You can reset it manually by setting that property to 0.

r.lastIndex = 0
like image 86
3 revs, 2 users 95%user2437417 Avatar answered Oct 28 '22 12:10

3 revs, 2 users 95%user2437417