« Back to Index

The difference between JavaScript’s exec and match methods is subtle but important, and I always forget…

View original Gist on GitHub

regex.js

var str = "The quick brown fox jumped over the box like an ox with a sox in its mouth";

str.match(/\w(ox)/g); // ["fox", "box", "sox"]

// match (when used with a 'g' flag) returns an Array with all matches found
// if you don't use the 'g' flag then it acts the same as the 'exec' method.

str.match(/\w(ox)/); // ["fox", "ox"]
/\w(ox)/.exec(str);  // ["fox", "ox"]

// the exec method returns an Array where the first index is the match and all other indexes are capturing groups
// note: adding a 'g' flag has no effect on the returned Array

/\w(ox)/g.exec(str);  // ["fox", "ox"]

// although you can use a while loop with the exec method to find successive matches

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;
  console.log(msg);
}

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