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
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.