Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 803
Shankar Avatar asked Sep 01 '17 23:09

Shankar


1 Answers

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"))
like image 135
Dekel Avatar answered Oct 20 '22 13:10

Dekel