JavaScript: String.prototype.match

By Xah Lee. Date: . Last updated: .
str.match(regex_or_str)
If there's no global flag g in regex, return a array of captured groups.
If there's global flag g, return a array of all occurrences.
Return null if no match. [see RegExp Flags]
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 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 → (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)

[see Regex Functions]

Without Global Flag: Get Captured Groups

Get all captured groups.

// capture attribute values in a image tag

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

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

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"
]
] */

With Global Flag: Get All Occurrences

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

console.log(
  txt.match(/[\w]+.jpg/g),
);
// [ "cat.jpg", "dog.jpg", "house.jpg" ]

Combinatorial Test

Yes capture, no global flag

const gx = /(\d)/;
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "2" ]
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "2" ]
console.log(gx.lastIndex); // 0

Yes capture, yes global flag

const gx = /(\d)/g;
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "3" ]
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "3" ]
console.log(gx.lastIndex); // 0

No capture, no global flag

const gx = /\d/;
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2" ]
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2" ]
console.log(gx.lastIndex); // 0

No capture, yes global flag

const gx = /\d/g;
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "3" ]
console.log(gx.lastIndex); // 0
console.log("a2cd3f".match(gx)); // [ "2", "3" ]
console.log(gx.lastIndex); // 0
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

String

prototype