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

后端 未结 24 2459
孤城傲影
孤城傲影 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: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!"
    

提交回复
热议问题