How can we find by index and replace it with a string? (see expected outputs below)
I tried the code below, but it also replaces the next string. (from these stack)
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
Expected output:
var toReplace = "!!";
1. "Hello World" ==> .replaceAt(5, toReplace) ===> "Hello!!World"
2. "Hello World" ==> .replaceAt(2, toReplace) ===> "He!!lo World"
Note: toReplace variable could be dynamic.
The second substring index should be 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, "!!!"))
Is it possible to add the string as a parameter in an ES6 function?
const replaceAt = (index, replacement, string) => {
return string[:index] + replacement + string[index+1:]
}