Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .replace() at a specific index

Is there a function that can replace a string within a string once at a specific index? Example:

var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",10);

and the resultant output would be "my text is your text", Or:

var string1="my text is my text";
var string2="my";
string1.replaceAt(string2,"your",0);

in which case the result would be "your text is my text".

like image 733
Joe Thomas Avatar asked May 04 '14 02:05

Joe Thomas


People also ask

How do I replace a particular index?

The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index.

How do you replace a specific index in Python?

As strings are immutable in Python, just create a new string which includes the value at the desired index. You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.


1 Answers

function ReplaceAt(input, search, replace, start, end) {
    return input.slice(0, start)
        + input.slice(start, end).replace(search, replace)
        + input.slice(end);
}

jsfiddle here

PS. modify the code to add empty checks, boundary checks etc.

like image 83
Alex from Jitbit Avatar answered Sep 22 '22 05:09

Alex from Jitbit