最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论