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

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

    In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

    You'll need to define the replaceAt() function yourself:

    String.prototype.replaceAt = function(index, replacement) {
        return this.substr(0, index) + replacement + this.substr(index + replacement.length);
    }
    

    And use it like this:

    var hello = "Hello World";
    alert(hello.replaceAt(2, "!!")); // Should display He!!o World
    
    0 讨论(0)
  • 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
    })
    
    0 讨论(0)
  • 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}`);
    }
    <input type="number" id="replaceAt" min="1" max="44" oninput="replaceAt()"/>

    0 讨论(0)
  • 2020-11-21 08:20

    var str = "hello world";
    console.log(str);
    var arr = [...str];
    arr[0] = "H";
    str = arr.join("");
    console.log(str);

    0 讨论(0)
  • 2020-11-21 08:23

    You could try

    var strArr = str.split("");
    
    strArr[0] = 'h';
    
    str = strArr.join("");
    
    0 讨论(0)
  • 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);
    }
    <button onclick="rep();">click</button>

    0 讨论(0)
提交回复
热议问题