Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count inside of a javascript regular expression?

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).

like image 351
Ternary Avatar asked Sep 01 '26 08:09

Ternary


1 Answers

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.

like image 154
Brandon Buck Avatar answered Sep 03 '26 22:09

Brandon Buck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!