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

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

    There is no replaceAt function in JavaScript. You can use the following code to replace any character in any string at specified position:

    function rep() {
        var str = 'Hello World';
        str = setCharAt(str,4,'a');
        alert(str);
    }
    
    function setCharAt(str,index,chr) {
        if(index > str.length-1) return str;
        return str.substring(0,index) + chr + str.substring(index+1);
    }

提交回复
热议问题