Skip to content

Instantly share code, notes, and snippets.

@anggiaj
Created November 30, 2016 12:56
Show Gist options
  • Save anggiaj/a2ee0a8a99c9ea6631b8e9705acb5230 to your computer and use it in GitHub Desktop.
Save anggiaj/a2ee0a8a99c9ea6631b8e9705acb5230 to your computer and use it in GitHub Desktop.
php like preg_match_all function
// NOTE: make sure your engine supports tail-call optimization
function matchAll(re, text) {
return (function find(acc) {
const match = re.exec(text);
if (match) {
acc.push(match);
return find(acc);
}
return acc;
})([]);
}
const re = /ola/ig; // don't forget the `g` flag :-)
const text = 'ola bola la ola';
matchAll(re, text);
// output
// [
// [ 'ola', index: 0, input: 'ola bola la ola' ],
// [ 'ola', index: 5, input: 'ola bola la ola' ],
// [ 'ola', index: 12, input: 'ola bola la ola' ]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment