How do I stick a counter in a javascript regular expression substitution?
The question is answered here for Perl/PCREs.
I've tried the obvious string.replace(/from/g, "to "+(++count)), which is no good (the ++count is evaluated once at the start of the string.replace, it seems).
You can pass along a function that is called per match to the replace:
// callback takes the match as the first parameter and then any groups as
// additional, left it empty because I'm not using them in the function.
string.replace(/from/g, function() {
return "to " + (++count);
});
I've found this to be an extremely handy tool in replacing complex string portions (like user comments with embedded codes) on the client side to ease the burden a bit on the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With