给定起始位置和长度,如何替换字符串的子字符串?
我希望有这样的事情:
var string = "This is a test string";
string.replace(10, 4, "replacement");
所以这string
将等于
"this is a replacement string"
..但我找不到类似的东西。
任何帮助表示赞赏。
给定起始位置和长度,如何替换字符串的子字符串?
我希望有这样的事情:
var string = "This is a test string";
string.replace(10, 4, "replacement");
所以这string
将等于
"this is a replacement string"
..但我找不到类似的东西。
任何帮助表示赞赏。
像这样:
var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length);
您可以将其添加到字符串的原型中:
String.prototype.splice = function(start,length,replacement) {
return this.substr(0,start)+replacement+this.substr(start+length);
}
(之所以这样称呼splice
,是因为它与同名的Array函数非常相似)
对于它的价值,这个函数将基于两个索引而不是第一个索引和长度来替换。
splice: function(specimen, start, end, replacement) {
// string to modify, start index, end index, and what to replace that selection with
var head = specimen.substring(0,start);
var body = specimen.substring(start, end + 1); // +1 to include last character
var tail = specimen.substring(end + 1, specimen.length);
var result = head + replacement + tail;
return result;
}
短正则表达式版本:
str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word);
例子:
String.prototype.sreplace = function(start, length, word) {
return this.replace(
new RegExp("^(.{" + start + "}).{" + length + "}"),
"$1" + word);
};
"This is a test string".sreplace(10, 4, "replacement");
// "This is a replacement string"
演示:http: //jsfiddle.net/9zP7D/