JS: String.prototype.matchAll

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2020)

str.matchAll(findStr)

findStr is a string, it is converted to regex regex_obj by RegExp with added regex flag g. Then str.matchAll(regex_obj) is called.

// if regex is string, need double backslash
console.log(Array.from("year 2010, 2015, and 2020".matchAll("\\d+"), (x) => x[[0]]));
// [ "2010", "2015", "2020" ]

// in string, single backslash d is just d
console.log(Array.from("year 2010, 2015, and 2020".matchAll("\d+"), (x) => x[[0]]));
// [ "d" ]
str.matchAll(regex_obj)

Return a Iterable Object of all occurrences and captures, or return null if no match.

regex_obj must have the regex flag g, else it's error.

For each item in result, it is an array with meaning like this:

[matched_str, capture_1, capture_2, etc]

(Note: Captures are always substring of the matched_str.)

the result array has these properties:

  • index → The beginning position of 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.
console.log(Array.from("year 2010, 2015, and 2020".matchAll(/\d\d(\d)(\d)/g)));
/*
[
  [
    "2010",
    "1",
    "0",
    index: 5,
    input: "year 2010, 2015, and 2020",
    groups: undefined
  ],
  [
    "2015",
    "1",
    "5",
    index: 11,
    input: "year 2010, 2015, and 2020",
    groups: undefined
  ],
  [
    "2020",
    "2",
    "0",
    index: 21,
    input: "year 2010, 2015, and 2020",
    groups: undefined
  ]
]
*/
// get the matches
console.log(Array.from("year 2010, 2015, and 2020".matchAll(/\d+/g), (x) => x[[0]]));
// [ "2010", "2015", "2020" ]

Require regex flag g

If the argument is a regex object, it must have the regex flag g, else its error.

// the regex object should have flag g

// "year 1999".matchAll(/\d{4}/)

// error: Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument

JavaScript. Regular Expression

JS String.prototype