How to replace a substring between two indices

后端 未结 6 1968
挽巷
挽巷 2020-12-08 09:23

I want to replace text between two indices in Javascript, something like:

str = \"The Hello World Code!\";
str.replaceBetween(4,9,\"Hi\");
// outputs \"The          


        
6条回答
  •  臣服心动
    2020-12-08 10:13

    There is no such method in JavaScript. But you can always create your own:

    String.prototype.replaceBetween = function(start, end, what) {
      return this.substring(0, start) + what + this.substring(end);
    };
    
    console.log("The Hello World Code!".replaceBetween(4, 9, "Hi"));

提交回复
热议问题