Skip to content

Instantly share code, notes, and snippets.

@jinwyp
Forked from Integralist/regex.js
Created July 6, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jinwyp/b60ebcdf7358c78c0167e3ecddedffbc to your computer and use it in GitHub Desktop.
Save jinwyp/b60ebcdf7358c78c0167e3ecddedffbc to your computer and use it in GitHub Desktop.
The difference between JavaScript's `exec` and `match` methods is subtle but important, and I always forget...
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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment