How to replace a substring between two indices

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

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

The indices and the string are both dynamic.

How could I go about doing this?


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"));

The accepted answer is correct, but I wanted to avoid extending the String prototype:

function replaceBetween(origin, startIndex, endIndex, insertion) {
  return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}

Usage:

replaceBetween('Hi World', 3, 7, 'People');

// Hi People

If using a concise arrow function, then it's:

const replaceBetween = (origin, startIndex, endIndex, insertion) =>
  origin.substring(0, startIndex) + insertion + origin.substring(endIndex);

If using template literals, then it's:

const replaceBetween = (origin, startIndex, endIndex, insertion) =>
  `${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;

There is an Array.splice method in JavaScript which does this job, but no String.splice. If you convert your string into an array, however:

var str = "The Hello World Code!";
var arr = str.split('');
var removed = arr.splice(4,5,"Hi"); // arr is modified
str = arr.join('');

This is how it worked for me.

var str = "The Hello World Code!";
var newStr="Hi"

var startIndex= 4;  // start index of 'H' from 'Hello'
var endIndex= 8; // end index of 'o' from 'Hello'
var preStr = str.substring(0, startIndex);
var postStr = str.substring(endIndex+1, str.length - 1);
var result = preStr+newStr+postStr;);     // outputs "The Hi World Code"

fiddle: http://jsfiddle.net/ujvus6po/1/