JavaScript: String.prototype.match

By Xah Lee. Date: . Last updated: .
str.match(regex_or_str)
Return a Array of captured groups or all occurences. Return null if no match.
  • If there's no flag g in regex, return captured groups.
  • If there's flag g in regex, return all occurrences. (any capture group in regex is ignored) (Tip: if you want all occurrences, use matchAll. [see String.prototype.matchAll])

If arg is a string, it is converted to regex first by RegExp.
In result array, index 0 is the whole matched string, index 1 is 1st captured group or occurrence, index 2 is the 2nd, etc.
The result array have these properties (their values are undefined if no g flag):
  • index → The beginning position of first occurrence.
  • input → The input string.
  • groups → (JS2018) A object. Key is name of named capture group. Value is corresponding substring, or undefined if there is none.
Return Value
has global flagno global flag
has capture groupall occurrencescaptured groups
no capture groupall occurrences1st match (array of 1 item)

Without Global Flag: Get Captured Groups

Get all captured groups.

// capture attribute values in a image tag

const regex =
  /<img src="([^"]+)" alt="([^"]+)" width="([^"]+)" height="([^"]+)">/;

const txt = '<div><img src="cat.jpg" alt="my cat" width="600" height="400">';

const result = txt.match(regex);

console.log(result);

// [
//   '<img src="cat.jpg" alt="my cat" width="600" height="400">',
//   "cat.jpg",
//   "my cat",
//   "600",
//   "400"
// ]

console.log(Reflect.ownKeys(result));

// [
//   "0",      "1",
//   "2",      "3",
//   "4",      "length",
//   "index",  "input",
//   "groups"
// ]

// start of match
console.log(result.index);
// 5

// original string
console.log(result.input === txt);
// true

// no named capture
console.log(result.groups);
// undefined

With Global Flag: Get All Occurrences

// get all image file names

const regex = /[\w]+.jpg/g;

const txt = `
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
<img src="house.jpg" alt="house">
`;

const result = txt.match(regex);

console.log(result);
// [ "cat.jpg", "dog.jpg", "house.jpg" ]

console.log(Reflect.ownKeys(result));
// [ "0", "1", "2", "length" ]

// start of match
console.log(result.index);
// undefined

// original string
console.log(result.input);
// undefined

// no named capture
console.log(result.groups);
// undefined

JavaScript Regular Expression


BUY
ΣJS
JavaScript in Depth

JS Obj Reference

String

prototype