I want to replace text between two indices in Javascript, something like:
str = \"The Hello World Code!\";
str.replaceBetween(4,9,\"Hi\");
// outputs \"The
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/
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);
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('');
Another approach when you need to totally replace a string at a specific index, with quite the same function call with String.prototype.replace
could be this:
String.prototype.replaceAt = function(index, fromString, toString) {
let hasWrongParams = typeof index !== 'number'
|| !fromString || typeof fromString !== 'string'
|| !toString || typeof toString !== 'string';
if(hasWrongParams) return '';
let fromIndex = index;
let toIndex = index + fromString.length;
return this.substr(0, fromIndex) + toString + this.substr(toIndex);
}
https://gist.github.com/kwnccc/9df8554474e39f4b17a07efbbdf7971c
For example:
let string = 'This is amazing world, it's still amazing!';
string.replaceAt(8, 'amazing', 'worderful');
// 'This is worderful world, it's still amazing!'
string.replaceAt(34, 'amazing', 'worderful');
// 'This is amazing world, it's still worderful!'
A more robust version of VisioN's solution that detects out of range errors and throws meaningful and easy to debug RangeError
s. If you want, you can extend the String.prototype
as well.
function replaceString(str, start, end, replace) {
if (start < 0 || start > str.length) {
throw new RangeError(`start index ${start} is out of the range 0~${str.length}`);
}
if (end > str.length || end < start) {
throw new RangeError(`end index ${end} is out of the range ${start}~${str.length}`);
}
return str.substring(0, start) + replace + str.substring(end);
}
// replace in the middle of the string, replacement string can be any length
console.log(replaceString("abcdef", 2, 4, "hhhh")); // output: "abhhhhef"
// insert in the front of the string, start and end index equal to 0
console.log(replaceString("abcdef", 0, 0, "hhhh")); // output: "hhhhabcdef"
// append at the end of the string, start and end index equal to the length of the string
console.log(replaceString("abcdef", 6, 6, "hhhh")); // output: "abcdefhhhh"
// error 1: start index is greater than end index
// console.log(replaceString("abcdef", 4, 2, "hhhh")); // output: RangeError: end index 2 is out of the range 4~6
// error 2: start/end index is less than 0
// console.log(replaceString("abcdef", -2, 2, "hhhh")); // output: RangeError: start index -2 is out of the range 0~6
// error 3: start/end index is greater than length of the string
// console.log(replaceString("abcdef", 3, 20, "hhhh")); // output: RangeError: end index 20 is out of the range 3~6