[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll [Back]  [Original]

String.prototype.matchAll() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

String.prototype.matchAll()

Baseline

20201

matchAll() String

const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// : Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// : Array ["test2", "e", "st2", "2"]

js
matchAll(regexp)

regexp

Symbol.matchAll

regexp RegExp RegExp new RegExp(regexp, 'g')

regexp (g) TypeError

RegExp.prototype.exec()

TypeError

regexp (g) flags "g"

String.prototype.matchAll Symbol.matchAll RegExp.prototype[Symbol.matchAll]()

Regexp.prototype.exec() matchAll()

matchAll() JavaScript regexp.exec /g

js
const regexp = /foo[a-z]*/g;
const str = "table football, foosball";
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(
    `Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,
  );
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.

matchAll() while g exec for...ofArray.from()

js
const regexp = /foo[a-z]*/g;
const str = "table football, foosball";
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(
    `Found ${match[0]} start=${match.index} end=${
      match.index + match[0].length
    }.`,
  );
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.

//  for...of 
//  matchAll 
Array.from(str.matchAll(regexp), (m) => m[0]);
// [ "football", "foosball" ]

matchAll (g)

js
const regexp = /[a-c]/;
const str = "abc";
str.matchAll(regexp);
// TypeError

matchAll regexp regexp.exec() lastIndex

js
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]

regexp.exec() lastIndex

String.prototype.match()

matchAll

match() g

js
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";

str.match(regexp); // ['test1', 'test2']

matchAll

js
const array = [...str.matchAll(regexp)];

array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]

matchAll() RegExp [Symbol.matchAll]()

Symbol.matchAll Symbol.matchAll matchAll()

js
const str = "Hmm, this is interesting.";

str.matchAll({
  [Symbol.matchAll](str) {
    return [["Yes, it's interesting."]];
  },
}); // [["Yes, it's interesting."]] 

ECMAScript 2027 LanguageSpecification
# sec-string.prototype.matchall


Web Proxy Viewer  |  New URL  |  Original Page