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