Skip to content

Instantly share code, notes, and snippets.

@krackers
Forked from TheBrenny/matchAll polyfill.js
Created February 23, 2023 22:08
Show Gist options
  • Save krackers/b3c266743c6e19b3b7301ba2c4693579 to your computer and use it in GitHub Desktop.
Save krackers/b3c266743c6e19b3b7301ba2c4693579 to your computer and use it in GitHub Desktop.
A polyfill for the String.prototype.matchAll method. Only available in Node12+ and most browsers.

I know almost all browsers and Node installations support it, but Node 11 doesn't, and I kinda need that right now. So enjoy!

// Useable just like the normal matchAll:

let data = "Hello World!";
let rx = /[A-Z]/g;
let matches = [...data.matchAll(rx)];

console.table(matches);
/* Expected output:
┌─────────┬─────┬───────┬────────────────┬───────────┐
│ (index) │  0  │ index │     input      │  groups   │
├─────────┼─────┼───────┼────────────────┼───────────┤
│    0    │ 'H' │   0   │ 'Hello World!' │ undefined │
│    1    │ 'W' │   6   │ 'Hello World!' │ undefined │
└─────────┴─────┴───────┴────────────────┴───────────┘
*/
if(!String.prototype.matchAll) {
String.prototype.matchAll = function (rx) {
if (typeof rx === "string") rx = new RegExp(rx, "g"); // coerce a string to be a global regex
rx = new RegExp(rx); // Clone the regex so we don't update the last index on the regex they pass us
let cap = []; // the single capture
let all = []; // all the captures (return this)
while ((cap = rx.exec(this)) !== null) all.push(cap); // execute and add
return all; // profit!
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment