How to replace a substring between two indices
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 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"));