Skip to content

Instantly share code, notes, and snippets.

@simonw
Created October 4, 2010 17:02
Show Gist options
  • Save simonw/610054 to your computer and use it in GitHub Desktop.
Save simonw/610054 to your computer and use it in GitHub Desktop.
/* Inspired by Python's useful re.findall method */
function findall(regex, str) {
var matches = [], m;
regex.lastIndex = 0;
while (m = regex.exec(str, regex.lastIndex)) {
matches[matches.length] = m;
}
return matches;
}
/* Example usage:
var matches = findall(/\d+/, '123 456 789');
*/
@RandomEtc
Copy link

When I ran this in node and in Firefox I got stuck in an infinite loop beucase regex.lastIndex is always 0 - I think your function requires regex to be global so the example regex should be /\d+/g?

I think you can get the same result with '123 456 789'.match(/\d+/g)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment