How do I replace a character at a particular index in JavaScript?

后端 未结 24 2091
孤城傲影
孤城傲影 2020-11-21 07:23

I have a string, let\'s say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?

var str = \"h         


        
24条回答
  •  难免孤独
    2020-11-21 08:19

    In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

    You'll need to define the replaceAt() function yourself:

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

    And use it like this:

    var hello = "Hello World";
    alert(hello.replaceAt(2, "!!")); // Should display He!!o World
    

提交回复
热议问题