JS: RegExp.prototype.exec

By Xah Lee. Date: . Last updated: .


Match regex pattern in string string.

Return 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

const myText = '<img class="i" src="cat.jpg" alt="my cat">';

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

const myResult = re.exec(myText);

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

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. (instead of captured groups)

[see JS: String.prototype.match]


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

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: RegExp Syntax
  3. JS: Regex Find/Replace
  4. JS: RegExp Object
  5. JS: RegExp Constructor
  6. JS: RegExp.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.