Javascript Regex Finding Successive Match


If your regular expression uses the "g" flag, you can use the exec() method 
multiple times to find successive matches in the same string. When you do so, 
the search starts at the substring of str specified by the regular expression's 
lastIndex property (test() will also advance the lastIndex property). For 
example, assume you have this script:

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;

The above code displays the following text:

Found abb. Next match starts at 3
Found ab. Next match starts at 9

Do not place the regular expression literal (or RegExp constructor) within the 
while condition or it will create an infinite loop if there is a match due to 
the lastIndex property being reset upon each iteration. Also be sure that the 
global flag is set or a loop will occur here also.

var matches = /(hello \S+)/.exec('This is a hello world!');
console.log(matches[1]); // will log a message containing 'hello world!'.

var match2 = regex.exec(text);
console.log(match2[0]);       // logs 'на' [did not log 'text']
console.log(regex.lastIndex); // logs '15'
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License