代码之家  ›  专栏  ›  技术社区  ›  Shankar

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

  •  8
  • Shankar  · 技术社区  · 9 年前

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

    在javascript或nodeJS中有什么方法可以做到这一点吗?

    2 回复  |  直到 9 年前
        1
  •  5
  •   Dekel    9 年前

    没有直接的方法使用内置 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"))
        2
  •  3
  •   Slai    8 年前

    正则表达式替代,但替换特定索引后的所有出现项:

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