12

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".

Joe Thomas
  • 5,807
  • 6
  • 25
  • 36
  • 2
    `string1 = string1.slice(0,10) + string1.slice(10).replace(string2, "your");` - wrap in a custom `replaceAt()` function if required. – nnnnnn May 04 '14 at 02:31
  • 1
    See also: http://stackoverflow.com/a/1431113/1757964 – APerson May 04 '14 at 02:31
  • Does this answer your question? [Replacing character at a particular index with a string in Javascript , Jquery](https://stackoverflow.com/questions/10784637/replacing-character-at-a-particular-index-with-a-string-in-javascript-jquery) – wesinat0r Dec 31 '19 at 04:33

2 Answers2

11
function 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.

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
0

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?

Community
  • 1
  • 1
Knetic
  • 2,099
  • 1
  • 20
  • 34