如何按范围替换字符串?

时间:2012-09-24 15:25:55

标签: javascript string replace

我需要按范围替换字符串 例如:

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');

但这只取代了第一个字符,我想要第一个到第三个

3 个答案:

答案 0 :(得分:19)

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"

答案 1 :(得分:3)

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"

答案 2 :(得分:0)

我会在这里做简单的substring电话

var str = "this is a string";
var result = "that" + str.substring(4);

查看有效的jsfiddle