最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using .replace() at a specific index - Stack Overflow

programmeradmin0浏览0评论

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 string1 = string1.slice(0,10) + string1.slice(10).replace(string2, "your"); - wrap in a custom replaceAt() function if required. – nnnnnn Commented May 4, 2014 at 2:31
  • 1 See also: stackoverflow.com/a/1431113/1757964 – APerson Commented May 4, 2014 at 2:31
  • Does this answer your question? Replacing character at a particular index with a string in Javascript , Jquery – wesinat0r Commented Dec 31, 2019 at 4:33
Add a comment  | 

2 Answers 2

Reset to default 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.

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?

发布评论

评论列表(0)

  1. 暂无评论