Replace the string after a specific index in javascript str.replace (from, to, indexfrom)

I like replacing the string after a specific index.

ex:

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

Is there a way to do this in javascript or in nodeJS?

+4
source share
2 answers

There is no direct way to use the built-in function replace, but you can always create a new function for it:

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 codeHide result
+2
source

Shorter and slower alternative:

s = 'abcabcabc'

console.log(s.replace(/a/g, (a, i) => i > 2 ? 'z' : 'a'))
Run codeHide result
0
source

Source: https://habr.com/ru/post/1684928/


All Articles