gpt4 book ai didi

javascript - 我如何计算 javascript 正则表达式的内部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:35:09 25 4
gpt4 key购买 nike

如何在 javascript 正则表达式替换中添加一个计数器?

问题是answered here用于 Perl/PCRE。

我已经尝试了明显的 string.replace(/from/g, "to "+(++count)),这是不好的(++count 在string.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);
});

我发现这是一个非常方便的工具,可以在客户端替换复杂的字符串部分(例如带有嵌入式代码的用户评论),从而减轻服务器的负担。

关于javascript - 我如何计算 javascript 正则表达式的内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15827010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com