Javascript - PHP 在 JavaScript 上的 Substr() 替代品



我在javasctipt上使用一个长字符串,我必须替换我无法预先确定其长度和值的子字符串,其中我不能使用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"));

在 JavaScript 中,你有substrsubstring

var str = "mystr";
console.log(str.substr(1, 2));
console.log(str.substring(1, 2));

它们在第二个参数上有所不同。对于substr是长度(就像你问的那个),对于substring是最后一个索引位置。你不要求第二个,而只是记录它。

没有内置函数可以替换为基于索引和长度的新内容。扩展字符串的原型(或简单地定义为函数)并使用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'));

最新更新