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

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

    Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.

    replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 
    

    Working example: https://codesandbox.io/s/ov7zxp9mjq

    function replaceAt(indexArray, [...string]) {
        const replaceValue = i => string[i] = {string[i]};
        indexArray.forEach(replaceValue);
        return string;
    }
    

    And here is another alternate method

    function replaceAt(indexArray, [...string]) {
        const startTag = '';
        const endTag = '';
        const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
        indexArray.forEach(tagLetter);
        return string.join('');
    }
    

    And another...

    function replaceAt(indexArray, [...string]) {
        for (let i = 0; i < indexArray.length; i++) {
            string = Object.assign(string, {
              [indexArray[i]]: {string[indexArray[i]]}
            });
        }
        return string;
    }
    

提交回复
热议问题