Javascript - RegExp exec() with global flag

Introduction

The exec() method returns information about one match at a time even if the pattern is global.

When the global flag is set, calling exec() on the same string multiple times will return the first match.

When the g flag is set, each call to exec() moves further into the string looking for matches:

Demo

var text = "at, mat, dat, gat";
var pattern1 = /.at/;

var matches = pattern1.exec(text);
console.log(matches.index);        //from w  w  w . ja  va 2s  .co  m
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

matches = pattern1.exec(text);
console.log(matches.index);       
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

var pattern2 = /.at/g;

var matches = pattern2.exec(text);
console.log(matches.index);       
console.log(matches[0]);         
console.log(pattern2.lastIndex);  

matches = pattern2.exec(text);
console.log(matches.index);       
console.log(matches[0]);         
console.log(pattern2.lastIndex);

Result

pattern1 is not global, so each call to exec() returns the first match only ("cat").

pattern2 is global, so each call to exec() returns the next match in the string until the end of the string is reached.

In global matching mode, lastIndex is incremented after each call to exec(), but it remains unchanged in non global mode.

Related Topic