Javascript在搜索的特定索引处使用.replace()

it *_*nce 10 javascript

是否有一个函数可以在字符串的特定索引处替换字符串中的字符串一次?例:

var string1="my text is my text and my big text";
var string2="my";
string1.replaceAt(string2,"your",2);
Run Code Online (Sandbox Code Playgroud)

结果输出将是"我的文字是我的文字和你的大文字"

Fra*_*erZ 6

您可以通过一些操作来完成此操作,而不需要任何正则表达式.

我用这个函数来获取字符串中另一个字符串的位置(索引).

从那里开始,就像从开头到找到的索引返回一个子串一样简单,注入你的替换,然后返回其余的字符串.

function replaceAt(s, subString, replacement, index) {
  const p = s.split(subString, index+1).join(subString);
  return p.length < s.length ? p + replacement + s.slice(p.length + subString.length) : s;
}

console.log(replaceAt("my text is my text and my big text", "my", "your", 2))
console.log(replaceAt("my text is my text and that's all", "my", "your", 2))
console.log(replaceAt("my text is my my my my text", "my", "your", 2))
Run Code Online (Sandbox Code Playgroud)