我需要按范围替换字符串示例:
string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";
但这必须是动态的。不能替换固定词...需要按范围
我试过了
result = string.replaceAt(0, 'that');
但这仅替换第一个字符,我想要第一个到第三个
我需要按范围替换字符串示例:
string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";
但这必须是动态的。不能替换固定词...需要按范围
我试过了
result = string.replaceAt(0, 'that');
但这仅替换第一个字符,我想要第一个到第三个
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 返回字符串的一部分,以我为例,它从字符 3 开始直到 str.length 以具有最后一个字符...
要替换字符串的中间,可以使用相同的逻辑...
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"