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