在javascript str.replace(from, to, indexfrom) 中的特定索引后替换字符串

Sha*_*kar 7 javascript frontend replace nodes node.js

我喜欢在特定索引后替换字符串。

前任:

var str = "abcedfabcdef"
    str.replace ("a","z",2)
    console.log(str) 
    abcedfzbcdef
Run Code Online (Sandbox Code Playgroud)

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

Dek*_*kel 6

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

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"))
Run Code Online (Sandbox Code Playgroud)