JS: String.prototype.match

By Xah Lee. Date: . Last updated: .
str.match(findStr)

The string findStr is converted to regex regex_obj by regex constructor RegExp, then str.match(regex_obj) is called.

str.match(regex_obj)

Return a array, or null if no match.

If regex_obj has Regex Flag g (global), the result is all occurences.

Else, the result is the first matched string and captured groups (if any). result is the same as regex_obj.exec(str). see JS: RegExp.prototype.exec

Example. get all occurrences

const xtext = "year 2026-10-24 3201-08-17";
const xresult = xtext.match(/\d\d\d\d-(\d\d)-(\d\d)/g);
console.log(xresult);
// [ "2026-10-24", "3201-08-17" ]

Example. get first match and all captures

/* get first match and all captures */
const xtext = "year 2026-10-24 3201-08-17";
const xresult = xtext.match(/\d\d\d\d-(\d\d)-(\d\d)/);
console.log(xresult);
/*
[
  "2026-10-24",
  "10",
  "24",
  index: 5,
  input: "year 2026-10-24 3201-08-17",
  groups: undefined
]
*/

/*
first match is "2026-10-24"
capture 1 is the month "10"
capture 2 is the date "24"
*/