admin 管理员组文章数量: 1086019
I am working with a long string on javasctipt and I have to replace substrings that I cant predetermine their length and value , where I can't use str.replace(/substr/g,'new string')
, which doesn't allow replacing a substring that I can just determine its start position and its length.
Is there a function that I can use like string substr (string, start_pos, length, newstring)
?
I am working with a long string on javasctipt and I have to replace substrings that I cant predetermine their length and value , where I can't use str.replace(/substr/g,'new string')
, which doesn't allow replacing a substring that I can just determine its start position and its length.
Is there a function that I can use like string substr (string, start_pos, length, newstring)
?
3 Answers
Reset to default 4You can use a bo of substr
and concatenation using +
like this:
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"));
In JavaScript you have substr
and substring
:
var str = "mystr";
console.log(str.substr(1, 2));
console.log(str.substring(1, 2));
They differ on the second parameter. For substr
is length (Like the one you asked) and for substring
is last index position. You don't asked for the second one, but just to document it.
There is no build-in function which replaces with new content based on index and length. Extend the prototype of string(or simply define as a function) and generate the string using String#substr
method.
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'));
本文标签: JavascriptPHP39s Substr() alternative on JavaScriptStack Overflow
版权声明:本文标题:Javascript - PHP's Substr() alternative on JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744073351a2528896.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论