I’ve seen str.replace(..., ...) passed a function for its second argument. What is passed to the function? It goes like this:
"string_test".replace(/(.*)_(.*)/, function(a, b) { return a + b; } )
How do you get it to pass the matched groups to the function? What are a and b in this case if anything? I’ve been getting undefined.
The first argument is the entirety of a match, and the rest represent the matched groups. Basically it’s like the array returned from
.match().If the regex has the “g” modifier, then obviously the function is called over and over again.
Example:
edit — in the function, if you want the matched groups as an array, you can do:
Of course, as I wrote above that’s what you get from the
.match()method too.