1

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.

Arvind Kumar Avinash
  • 62,771
  • 5
  • 54
  • 92
Johnny
  • 447
  • 2
  • 13
  • Does this answer your question? [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – Yosvel Quintero Arguelles Sep 22 '21 at 02:39
  • 1
    @YosvelQuinteroArguelles already add that link as reference in my description. pls check. working output is not I want :) – Johnny Sep 22 '21 at 02:40

2 Answers2

5

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, "!!!"))
Spectric
  • 27,594
  • 6
  • 14
  • 39
  • it only works for *!!*, it does not work in dynamic or in other string length like *!!@@*. I updated my description :) – Johnny Sep 22 '21 at 02:33
0

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:]
}