javascript - 在javascript中每次替换时增加一个数字

标签 javascript replace numbers increment str-replace

我想在每次 string.replace() 替换子字符串时递增一个数字。例如:

var string = "This is this";
var number = 0;
string.replace("is", "as");

当 string.replace 第一个是 This 的数字变为 1,然后第二个是 is 的数字变为 2 最后是 this 数字变为 3。 提前致谢...! :-)

最佳答案

您可以将函数传递给 .replace() 并返回值。您还需要使用全局正则表达式来替换所有实例。

var string = "This is this";
var number = 0;

document.body.textContent = string.replace(/is/g, function() {
    return ++number;
});

关于javascript - 在javascript中每次替换时增加一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30220584/

相关文章:

javascript - react native git 升级错误 : fatal: No remote repository specified

javascript - 当我编写脚本时,它显示 TypeError : menuLi[i] is undefined

javascript - 用 jquery 替换来自正则表达式匹配的文本

java - 在java中以一定精度显示 double

numbers - plotly tickformat 不应用德语区域设置数字格式

JavaScript历史记录错误: Going back seems broken

javascript,这个条件是什么意思?如果(显示 || 真){...}

python - .replace() 不替换元素

bash - 如果字符串在同一行中匹配,则基于位置替换文本 block

random - 需要帮助 - 使用 Autohotkey 脚本的简单随机数生成器