9

I like to replace a string after a specific index.

ex:

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

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

Shankar
  • 143
  • 2
  • 10

2 Answers2

6

There is no direct way using the builtin replace function but you can always create a new function for that:

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"))
Dekel
  • 60,707
  • 10
  • 101
  • 129
  • 1
    @user2969187 it replaces only the first instance after the index. To replace all occurrences, something like `str.betterReplace(/a/g,"z",2)` – Slai Sep 02 '17 at 00:54
  • Just for name-sake, would prefer to call it replaceAfter :) – msanjay Jan 12 '22 at 10:09
  • And to replace all, we can also use replaceAll inside the function (optionally passing a flag or naming the function so) – msanjay Jan 12 '22 at 11:33
3

Regular expression alternative, but replaces all occurrences after specific index:

console.log( 'abcabcabc'.replace(/a/g, (s, i) => i > 2 ? 'z' : s) )
Slai
  • 22,144
  • 5
  • 45
  • 53