Created
November 30, 2016 12:56
-
-
Save anggiaj/a2ee0a8a99c9ea6631b8e9705acb5230 to your computer and use it in GitHub Desktop.
php like preg_match_all function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
})([]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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