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).
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).
- Do you mean that you want to know how many replacements were made? – d'alar'cop Commented Apr 5, 2013 at 6:05
- No. I want the replacement text to include the value of a counter that increments with each match. – Ternary Commented Apr 5, 2013 at 6:06
2 Answers
Reset to default 7You 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 plex string portions (like user ments with embedded codes) on the client side to ease the burden a bit on the server.
Using a callback might work:
var i = 0;
string.replace(/from/g, function(x){return "to " + i++;})
Cheers.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745195138a4616052.html
评论列表(0条)