如何查找字符串上的索引并替换?

アリ・*_*ディム 1 javascript

我们如何通过索引查找并用字符串替换它?(参见下面的预期产出)

我尝试了下面的代码,但它也替换了下一个字符串。(来自这些堆栈)

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

var hello = "hello world";
console.log(hello.replaceAt(2, "!!")); // He!!o World
Run Code Online (Sandbox Code Playgroud)

预期输出:

var toReplace = "!!";

1. "Hello World" ==> .replaceAt(5, toReplace) ===> "Hello!!World"
2. "Hello World" ==> .replaceAt(2, toReplace) ===> "He!!lo World"
Run Code Online (Sandbox Code Playgroud)

注意: toReplace变量可以是动态的。

Spe*_*ric 5

第二个子字符串索引应该是index+ 1:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + 1);
}

console.log("Hello World".replaceAt(5, "!!"))
console.log("Hello World".replaceAt(2, "!!"))
console.log("Hello World".replaceAt(2, "!!!"))
Run Code Online (Sandbox Code Playgroud)