المسارات / JavaScript / المرجع / String.matchAll

مرجع · String

String.matchAll

String.matchAll بترجّع iterator بكل التطابقات، ومعاها الـgroups والـindex لكل واحد. الـregex لازم يكون عنده g.

What does String.matchAll() do in JavaScript?

js
str.matchAll(regex)

match مع g بترجّع النصوص بس من غير تفاصيل. matchAll بتدّيك object لكل تطابق فيه index والـcapture groups. ولو الـregex من غير g بتترفض بـTypeError.

امتى أستخدمها

لما محتاج مكان كل تطابق أو الـgroups بتاعته.

البرهان

شُغّل على Node v26.14.0، والناتج منسوخ من التشغيل نفسه.

js
const text = 'a1 b22 c333';
console.log(text.match(/\d+/g));
for (const m of text.matchAll(/([a-z])(\d+)/g)) {
  console.log(m[1], m[2], m.index);
}
console.log(Array.from('x1'.matchAll(/\d/g)).length);
try {
  'x1'.matchAll(/\d/);
} catch (e) {
  console.log(e.constructor.name);
}
النتيجة
[ '1', '22', '333' ]
a 1 0
b 22 3
c 333 7
1
TypeError

الدروس اللي بتشرحها

الصفحة دي على MDN ↗

ابعت الصفحة لحد
واتسابتليجرامX
برهان

الدروس

اتحلّ 0 من 174 تمرين