Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
kqlambert Avatar asked Feb 14 '13 17:02

kqlambert


People also ask

How do I replace a substring with another substring?

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).

How do you replace a value in a string with another value?

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.


2 Answers

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"));
like image 83
VisioN Avatar answered Sep 20 '22 20:09

VisioN


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)}`; 
like image 24
Robin Wieruch Avatar answered Sep 20 '22 20:09

Robin Wieruch