在javascript str.replace中的特定索引之后replace一个string(from,to,indexfrom)

我喜欢在特定索引之后replacestring。

例如:

var str = "abcedfabcdef" str.replace ("a","z",2) console.log(str) abcedfzbcdef 

有没有什么办法在javascript或nodeJS做到这一点?

使用内置replace函数没有直接的方法,但是您总是可以为此创build一个新函数:

 String.prototype.betterReplace = function(search, replace, from) { if (this.length > from) { return this.slice(0, from) + this.slice(from).replace(search, replace); } return this; } var str = "abcedfabcdef" console.log(str.betterReplace("a","z","2")) 

更短更慢的替代scheme:

 s = 'abcabcabc' console.log(s.replace(/a/g, (a, i) => i > 2 ? 'z' : 'a'))