JS: RegExp.prototype.exec

By Xah Lee. Date: . Last updated: .
regex_obj.exec(string)

Match regex_obj pattern in string string.

  • Return a array if there is a match, else return null.
  • The first item is the first occurrence of matched part.
  • The rest items are captures, if any.

This method only get the first occurrence.


In result array, index 0 is the whole matched string, index 1 is first captured group, index 2 is the second, etc.
The result array have these properties:

  • index → The beginning position of first occurrence.
  • input → The input string.
  • groups → (new in ECMAScript 2018) A object. Key is name of named capture group. Value is corresponding substring, or undefined if there is none.

const xtext = `
src="glove_80_keyboard.jpg" alt="glove_80"
src="kinesis_360_keyboard.jpg" alt="kinesis_360"
src="uhk_80_keyboard.jpg" alt="uhk_80"
`;

// no capture.
// get first occurrence.
const xresult = /src="[^"]+" alt="[^"]+"/.exec(xtext)

console.log(xresult[0]);
// src="glove_80_keyboard.jpg" alt="glove_80"

console.log(xresult);
/*
[
  'src="glove_80_keyboard.jpg" alt="glove_80"',
  index: 1,
  input: "\n" +
    'src="glove_80_keyboard.jpg" alt="glove_80"\n' +
    'src="kinesis_360_keyboard.jpg" alt="kinesis_360"\n' +
    'src="uhk_80_keyboard.jpg" alt="uhk_80"\n',
  groups: undefined
]
*/
const xtext = `
src="glove_80_keyboard.jpg" alt="glove_80"
src="kinesis_360_keyboard.jpg" alt="kinesis_360"
src="uhk_80_keyboard.jpg" alt="uhk_80"
`;

// get the captures in first occurrence.
const xresult = /src="([^"]+)" alt="([^"]+)"/.exec(xtext)

console.log(xresult);
/*
[
  'src="glove_80_keyboard.jpg" alt="glove_80"',
  "glove_80_keyboard.jpg",
  "glove_80",
  index: 1,
  input: "\n" +
    'src="glove_80_keyboard.jpg" alt="glove_80"\n' +
    'src="kinesis_360_keyboard.jpg" alt="kinesis_360"\n' +
    'src="uhk_80_keyboard.jpg" alt="uhk_80"\n',
  groups: undefined
]
*/

If regex flag g is on, repeated call starts match at RegExp.prototype.lastIndex . (the end position of last found match) This allows you to find all occurrences in a loop. 🟢 TIP: better use String.prototype.matchAll

JavaScript. Regular Expression