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

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

    Generalizing Afanasii Kurakin's answer, we have:

    function replaceAt(str, index, ch) {
        return str.replace(/./g, (c, i) => i == index ? ch : c);
    }
    
    let str = 'Hello World';
    str = replaceAt(str, 1, 'u');
    console.log(str); // Hullo World

    Let's expand and explain both the regular expression and the replacer function:

    function replaceAt(str, index, newChar) {
        function replacer(origChar, strIndex) {
            if (strIndex === index)
                return newChar;
            else
                return origChar;
        }
        return str.replace(/./g, replacer);
    }
    
    let str = 'Hello World';
    str = replaceAt(str, 1, 'u');
    console.log(str); // Hullo World

    The regular expression . matches exactly one character. The g makes it match every character in a for loop. The replacer function is called given both the original character and the index of where that character is in the string. We make a simple if statement to determine if we're going to return either origChar or newChar.

提交回复
热议问题