JS: RegExp.prototype.exec

By Xah Lee. Date: . Last updated: .

regex.exec(string)

Match regex pattern in string string.

Returns a array of captured groups, or, return null if no match.

In result array, index 0 is the whole matched string, index 1 is first captured pattern, index 2 is the second captured pattern, etc.

// example of RegExp object “exec” method
// capture the attribute values in a image tag

var myText = '<img class="pict" src="cat.jpg" alt="my cat" width="600" height="400">';

var re = RegExp('<img class="([^"]+)" src="([^"]+)" alt="([^"]+)" width="([^"]+)" height="([^"]+)">');

var myResult = re.exec(myText);

console.log(myResult[0]); // <img class="i" src="cat.jpg" alt="my cat" width="600" height="400">
console.log(myResult[1]); // pict
console.log(myResult[2]); // cat.jpg
console.log(myResult[3]); // my cat
console.log(myResult[4]); // 600
console.log(myResult[5]); // 400

What is the difference between string.match(regex) and regex.exec(string)?

  1. Their arguments are reversed.
  2. if the global flag g is not used, regex.exec(string) return exactly the same thing as string.match(regex). If global flag is used, the “String.prototype.match” method returns a array of all occurrences of matched string. [see JS: String.prototoype.match]

Reference

ECMAScript® 2016 Language Specification#sec-regexp.prototype.exec

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: String Methods for RegExp
  3. JS: RegExp Object
  4. JS: RegExp Constructor
  5. JS: RegExp.prototype
  6. JS: RegExp Syntax
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon