Reputation: 1579
I want to get a portion of a string via .substring(indexStart, indexEnd)
then replace the same portion in the original string.
var portion = "my new house".substring(3, 6),
portion = "old";
// what's next?
Upvotes: 0
Views: 95
Reputation: 2715
You just need to call 'replace' on the original string to find the substring you gathered and replace it with the new desired string.
var oldString = "my new house my new house";
var subStr = oldString.substring(indexStart, indexEnd);
var newValue = "old";
var newString = oldString.replace(subStr, newValue);
Upvotes: 0
Reputation: 59283
You could take the surrounding substrings and concatenate:
var str = "my new house";
str = str.slice(0, 3) + "old" + str.slice(6);
console.log(str); // "my old house"
Of course, this is assuming you want to replace parts of the string marked off by certain indeces. If you just want to replace a word, you would use:
str = str.replace(/new/g, 'old');
(Omit the g
lobal flag to only replace the first occurrence.)
Upvotes: 4