I need to replace a string by range Example:
string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";
but this need to be dinamically. Cant be replace a fixed word ...need be by range
I have tried
result = string.replaceAt(0, 'that');
but this replace only the first character and I want the first to third
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
Java String replace() MethodThe replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
var str = "this is a string";
var newString = replaceRange(str, 0, 4, "that"); // "that is a string"
var str = "this is a string";
var newString = str.substr(3,str.length);
var result = 'that'+newString
substr returns a part of a string, with my exemple, it starts at character 3 up to str.length to have the last character...
To replace the middle of a string, the same logic can be used...
var str = "this is a string";
var firstPart = str.substr(0,7); // "this is "
var lastPart = str.substr(8,str.length); // " string"
var result = firstPart+'another'+lastPart; // "this is another string"
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