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

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

    You can use the following function to replace Character or String at a particular position of a String. To replace all the following match cases use String.prototype.replaceAllMatches() function.

    String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
        var retStr = this, repeatedIndex = 0;
        for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
            if (repeatedIndex == 0 && x == 0) {
                repeatedIndex = retStr.indexOf(matchkey);
            } else { // matchIndex > 0
                repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
            }
            if (x == matchIndex) {
                retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
                matchkey = null; // To break the loop.
            }
        }
        return retStr;
    };
    

    Test:

    var str = "yash yas $dfdas.**";
    
    console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
    console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
    

    Output:

    Index Matched replace :  yash yas $dfd*.**
    Index Matched replace :  yash ~as $dfdas.**
    
    0 讨论(0)
  • 2020-11-21 08:09

    This works similar to Array.splice:

    String.prototype.splice = function (i, j, str) {
        return this.substr(0, i) + str + this.substr(j, this.length);
    };
    
    0 讨论(0)
  • 2020-11-21 08:09

    If you want to replace characters in string, you should create mutable strings. These are essentially character arrays. You could create a factory:

      function MutableString(str) {
        var result = str.split("");
        result.toString = function() {
          return this.join("");
        }
        return result;
      }
    

    Then you can access the characters and the whole array converts to string when used as string:

      var x = MutableString("Hello");
      x[0] = "B"; // yes, we can alter the character
      x.push("!"); // good performance: no new string is created
      var y = "Hi, "+x; // converted to string: "Hi, Bello!"
    
    0 讨论(0)
  • 2020-11-21 08:10

    In Javascript strings are immutable so you have to do something like

    var x = "Hello world"
    x = x.substring(0, i) + 'h' + x.substring(i+1);
    

    To replace the character in x at i with 'h'

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

    I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone

    String.prototype.replaceAt=function(index, character) {
        if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
        else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
    
    }
    
    0 讨论(0)
  • 2020-11-21 08:12

    You can't. Take the characters before and after the position and concat into a new string:

    var s = "Hello world";
    var index = 3;
    s = s.substring(0, index) + 'x' + s.substring(index + 1);
    
    0 讨论(0)
提交回复
热议问题