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

后端 未结 24 2118
孤城傲影
孤城傲影 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:06

    Work with vectors is usually most effective to contact String.

    I suggest the following function:

    String.prototype.replaceAt=function(index, char) {
        var a = this.split("");
        a[index] = char;
        return a.join("");
    }
    

    Run this snippet:

    String.prototype.replaceAt=function(index, char) {
        var a = this.split("");
        a[index] = char;
        return a.join("");
    }
    
    var str = "hello world";
    str = str.replaceAt(3, "#");
    
    document.write(str);

提交回复
热议问题