我正在使用JavaScript处理一个长字符串,并且需要替换子字符串,但我无法预先确定它们的长度和值,因此不能使用str.replace(/substr/g,'new string')
,它不能替换我只能确定其起始位置和长度的子字符串。
是否有一种函数可以像string substr (string, start_pos, length, newstring)
这样使用?
我正在使用JavaScript处理一个长字符串,并且需要替换子字符串,但我无法预先确定它们的长度和值,因此不能使用str.replace(/substr/g,'new string')
,它不能替换我只能确定其起始位置和长度的子字符串。
是否有一种函数可以像string substr (string, start_pos, length, newstring)
这样使用?
substr
和连接符+
的组合,如下所示:
function customReplace(str, start, end, newStr) {
return str.substr(0, start) + newStr + str.substr(end);
}
var str = "abcdefghijkl";
console.log(customReplace(str, 2, 5, "hhhhhh"));
没有内置函数可以根据索引和长度替换新内容。扩展字符串的原型(或者简单地定义为一个函数),并使用String#substr
方法生成字符串。
String.prototype.customSubstr = function(start, length, newStr = '') {
return this.substr(0, start) + newStr + this.substr(start + length);
}
console.log('string'.customSubstr(2, 3, 'abc'));
// using simple function
function customSubstr(string, start, length, newStr = '') {
return string.substr(0, start) + newStr + string.substr(start + length);
}
console.log(customSubstr('string', 2, 3, 'abc'));
substr
和substring
:
var str = "mystr";
console.log(str.substr(1, 2));
console.log(str.substring(1, 2));
它们在第二个参数上不同。 对于 substr
是长度(就像你提出的那个问题),而对于 substring
是最后一个索引位置。 虽然您没有要求第二种方法,但需要记录它。
newStr
参数,那么这将无法工作:console.log(customReplace(str, 2, 5));
得到的输出为abundefinedfghijkl
。 - RomanPerekhrestnewStr
,那么这个函数本身有什么意义呢? - ibrahim mahrir