gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:41:16 26 4
gpt4 key购买 nike

我想在每次 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/

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