Javascript using .replace() at a specific index of the search

  • A+
Category:Languages

Is there a function that can replace a string within a string once at a specific index of the string? Example:

var string1="my text is my text and my big text"; var string2="my"; string1.replaceAt(string2,"your",2); 

and the resultant output would be "my text is my text and your big text"

 


Beside the use of a function for replacement, you could use the given variable for the position directly for decrementing and take this value as check for replacement or not.

const replace = (string, s, r, p) => string.replace(new RegExp(s, 'g'), m => p-- ? m : r); var string = 'my text is my text and my big text';  console.log(replace(string, 'my', 'your', 2));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: