Gwater17
Gwater17

Reputation: 2324

Using exec to find multiple matches JavaScript

I'm having trouble interpreting the following code from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

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

I'm confused by the while loop line. It seems to set myArray to the result of calling exec on the string str and says to continue if its not equal to null.

What I don't get is how the program knows to start searching from the last index where a match was found. To me it looks like this should be an infinite loop b/c I can't see where it says to start searching from the next index in an array.

Also, is there any reason to use exec to find multiple matches rather than just using match? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Upvotes: 1

Views: 1136

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

The lastIndex value is modified by the regex engine internally once you pass a regex with a global modifier to the RegExp#exec.

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).

Also, see 15.10.6.2 RegExp.prototype.exec(string) for the exact RegExp#exec specs. Especially:

  1. If global is true,
      a. Call the [[Put]] internal method of R with arguments "lastIndex", e, and true.

An infinite loop cannot occur since the pattern does not match an unancored empty string. It is var myRe = /ab*/g;, so a is oligatory in the input to return a valid match. If it were var myRe = /a*/g;, then there would be an infinite loop.

Also, check the Zero-Length regexes and infinite matches? thread.

Upvotes: 1

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94359

What I don't get is how the program knows to start searching from the last index

In your regexp myRe there is a property .lastIndex that tells where .exec should start parsing.

.exec is useful when you want to parse a string piece by piece instead of all in once.

For more information on how .exec works, you can take a look at this page on MDN.

Upvotes: 0

Related Questions