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
  • 71,965
  • 6
  • 74
  • 110
  • 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 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 :) – アリ・ナディム 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
  • 30,714
  • 6
  • 20
  • 43
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:]
}