Skip to content

Instantly share code, notes, and snippets.

@bathos
Created December 30, 2019 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bathos/2d1c9f7ab3c1250ee33bac4213f4a1c4 to your computer and use it in GitHub Desktop.
Save bathos/2d1c9f7ab3c1250ee33bac4213f4a1c4 to your computer and use it in GitHub Desktop.
observing-last-index-values.js
function matchAllButUpdateOriginalRegExp(regExp, string) {
return regExp[Symbol.matchAll].call({
constructor: { [Symbol.species]: function() { return regExp; } },
flags: regExp.flags,
lastIndex: regExp.lastIndex
}, string);
}
const pattern = /./g;
console.group('Ordinary behavior');
for (let match of 'abc'.matchAll(pattern)) {
console.log(match, pattern.lastIndex);
}
console.groupEnd();
console.group('Subversive shenanigans');
for (let match of matchAllButUpdateOriginalRegExp(pattern, 'abc')) {
console.log(match, pattern.lastIndex);
}
console.groupEnd();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment