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

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

    Here is my solution using the ternary and map operator. More readable, maintainable end easier to understand if you ask me.

    It is more into es6 and best practices.

    function replaceAt() {
      const replaceAt = document.getElementById('replaceAt').value;
    
      const str = 'ThisIsATestStringToReplaceCharAtSomePosition';
      const newStr = Array.from(str).map((character, charIndex) => charIndex === (replaceAt - 1) ? '' : character).join('');
    
      console.log(`New string: ${newStr}`);
    }

提交回复
热议问题