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]

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials