Is there a function that can replace a string within a string once at a specific index? Example:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",10);
and the resultant output would be "my text is your text", Or:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",0);
in which case the result would be "your text is my text".
Is there a function that can replace a string within a string once at a specific index? Example:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",10);
and the resultant output would be "my text is your text", Or:
var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",0);
in which case the result would be "your text is my text".
Share Improve this question asked May 4, 2014 at 2:29 Joe ThomasJoe Thomas 6,4076 gold badges28 silver badges38 bronze badges 3 |2 Answers
Reset to default 11function ReplaceAt(input, search, replace, start, end) {
return input.slice(0, start)
+ input.slice(start, end).replace(search, replace)
+ input.slice(end);
}
jsfiddle here
PS. modify the code to add empty checks, boundary checks etc.
From the "related questions" bar, this old answer seems to be applicable to your case. Replacing a single character (in my referenced question) is not very different from replacing a string.
How do I replace a character at a particular index in JavaScript?
string1 = string1.slice(0,10) + string1.slice(10).replace(string2, "your");
- wrap in a customreplaceAt()
function if required. – nnnnnn Commented May 4, 2014 at 2:31