Michael Wilson
Michael Wilson

Reputation: 1579

Get substring then replace

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

Answers (2)

jrkt
jrkt

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

tckmn
tckmn

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 global flag to only replace the first occurrence.)

Upvotes: 4

Related Questions