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

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

    One-liner using String.replace with callback (no emoji support):

    // 0 - index to replace, 'f' - replacement string
    'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
    // "fog"
    

    Explained:

    //String.replace will call the callback on each pattern match
    //in this case - each character
    'dog'.replace(/./g, function (character, index) {
       if (index == 0) //we want to replace the first character
         return 'f'
       return character //leaving other characters the same
    })
    

提交回复
热议问题