Is there a function that can replace a string within a string once at a specific index of the string? Example:
var string1="my text is my text and my big text";
var string2="my";
string1.replaceAt(string2,"your",2);
and the resultant output would be "my text is my text and your big 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.
The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
You can do this with a little bit of manipulation, not requiring any regex.
I used this function to fetch the position (index) of another string within a string.
From there, it's as simple as returning a substring from the beginning to the found index, injecting your replacement, and then returning the rest of the string.
function replaceAt(s, subString, replacement, index) {
const p = s.split(subString, index+1).join(subString);
return p.length < s.length ? p + replacement + s.slice(p.length + subString.length) : s;
}
console.log(replaceAt("my text is my text and my big text", "my", "your", 2))
console.log(replaceAt("my text is my text and that's all", "my", "your", 2))
console.log(replaceAt("my text is my my my my text", "my", "your", 2))
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