JavaScript ‘re.findall’ workalike

JavaScript Re.Findall Workalike

Having done a lot of low-complexity JavaScript and a lot of regex work in back-end languages like PHP and Python, I found myself stumped again trying to do something that is bread and butter in PHP and Python, but somewhat obfuscated in JS.
I also had the tingly feeling of deja vu, that I’d run into this particular brainfart before, but this time in order to prevent future memory failures and maybe even enrich the lives of other idiots like me searching google, I decided to blog about it.
Problem: there is no simple equivalent to ‘re.findall’ in JS. re.findall goes like this:

from re import findall
textvar = getsometext()
list_of_matches = findall('^foo\.([\S])+?', textvar)

The convenient part is that this is a very common operation to want to make, and there is a nice function that directly handles this requirement and returns the results. PHP is slightly less direct:

$matches = array();
preg_match_all('/^foo\.([\S])+?/', $textvar, $matches, PREG_SET_ORDER);

Slightly more obtuse; I tend to wrap this in a function called ‘findAll()’ in a base class somewhere.
JavaScript is a bit more work again ( as suggested by the Rhino book ):

var rx = new RegExp("^foo\.([\S])+?", "g");
var matches = new Array();
while((match = rx.exec(textvar)) !== null){

You could do this in a slightly different way off of the String object:

var matches = textVar.match(/^foo\.([\S])+?/g);

…but you only get the outer match, no the sub-matches from the parentheses. =/

Recent Posts

Scroll to Top