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?
Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
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)}`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With