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)
?
The JavaScript String replace() method returns a new string with a substring ( substr ) replaced by a new one ( newSubstr ). Note that the replace() method doesn't change the original string.
substr(…) is not strictly deprecated (as in “removed from the Web standards”), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.
The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). Parameters: Here the Startindex and Endindex describes the part of the string to be taken as substring. Here the Endindex is optional.
You can use a combo 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With