regex - How do I count inside of a javascript regular expression? - Stack Overflow

How do I stick a counter in a javascript regular expression substitution?The question is answered here

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

Share Improve this question edited May 23, 2017 at 12:14 CommunityBot 11 silver badge asked Apr 5, 2013 at 6:04 TernaryTernary 5974 silver badges8 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 7

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

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信