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

后端 未结 24 1972
孤城傲影
孤城傲影 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 07:58

    You can extend the string type to include the inset method:

    String.prototype.append = function (index,value) {
      return this.slice(0,index) + value + this.slice(index);
    };
    
    var s = "New string";
    alert(s.append(4,"complete "));

    Then you can call the function:

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

    There are lot of answers here, and all of them are based on two methods:

    • METHOD1: split the string using two substrings and stuff the character between them
    • METHOD2: convert the string to character array, replace one array member and join it

    Personally, I would use these two methods in different cases. Let me explain.

    @FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.

    @vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.

    But what will happen if I have to make quite a few replacements?

    I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:

    var str = "... {A LARGE STRING HERE} ...";
    
    for(var i=0; i<100000; i++)
    {
      var n = '' + Math.floor(Math.random() * 10);
      var p = Math.floor(Math.random() * 1000);
      // replace character *n* on position *p*
    }
    

    I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).

    Results:

    • TEST1: 195ms
    • TEST2: 6ms

    It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???

    What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.

    So, it's all about choosing the right tool for the job. Again.

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

    Lets say you want to replace Kth index (0-based index) with 'Z'. You could use Regex to do this.

    var re = var re = new RegExp("((.){" + K + "})((.){1})")
    str.replace(re, "$1A$`");
    
    0 讨论(0)
  • 2020-11-21 08:06

    Work with vectors is usually most effective to contact String.

    I suggest the following function:

    String.prototype.replaceAt=function(index, char) {
        var a = this.split("");
        a[index] = char;
        return a.join("");
    }
    

    Run this snippet:

    String.prototype.replaceAt=function(index, char) {
        var a = this.split("");
        a[index] = char;
        return a.join("");
    }
    
    var str = "hello world";
    str = str.replaceAt(3, "#");
    
    document.write(str);

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

    Generalizing Afanasii Kurakin's answer, we have:

    function replaceAt(str, index, ch) {
        return str.replace(/./g, (c, i) => i == index ? ch : c);
    }
    
    let str = 'Hello World';
    str = replaceAt(str, 1, 'u');
    console.log(str); // Hullo World

    Let's expand and explain both the regular expression and the replacer function:

    function replaceAt(str, index, newChar) {
        function replacer(origChar, strIndex) {
            if (strIndex === index)
                return newChar;
            else
                return origChar;
        }
        return str.replace(/./g, replacer);
    }
    
    let str = 'Hello World';
    str = replaceAt(str, 1, 'u');
    console.log(str); // Hullo World

    The regular expression . matches exactly one character. The g makes it match every character in a for loop. The replacer function is called given both the original character and the index of where that character is in the string. We make a simple if statement to determine if we're going to return either origChar or newChar.

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

    @CemKalyoncu: Thanks for the great answer!

    I also adapted it slightly to make it more like the Array.splice method (and took @Ates' note into consideration):

    spliceString=function(string, index, numToDelete, char) {
          return string.substr(0, index) + char + string.substr(index+numToDelete);
       }
    
    var myString="hello world!";
    spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"
    
    0 讨论(0)
提交回复
热议问题