5

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) ?

0

3 Answers 3

4

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"));

Sign up to request clarification or add additional context in comments.

3 Comments

this won't work if newStr argument is not passed in: console.log(customReplace(str, 2, 5)); gives abundefinedfghijkl
@RomanPerekhrest if newStr is not passed in then what is the point of the function itself?
you should consider this condition to get a more uniform solution
2

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.

2 Comments

is there anyway to use them to replace a string or characters by other ones?
Yes, you have to substring to the index you want and concatenate it to the next. Actually, this answer is pretty good: stackoverflow.com/a/42300623/1525495
2

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'));

1 Comment

i want to replace with other charachters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.