How can I replace some words in a string with some other words? For example:
var text1 = "This is a sentence. It is a pencil."
text2 = modify(text1);
I want text2 to be “That was a sentence. I was a pencil.”
So modify function replaces This->That , is->was
To replace all instances of the substring
iswithwasyou can use thereplace[MDN] method:Note that because
isis a part of the wordthis, it will actually returnIf you wanted to replace all instances of
ThistoThatandistowas, you could chain the calls to thereplacemethod.This will correctly do your replacement from
to
You can see this in action on jsFiddle.
Note that find and replace actions like this can always have unintended consequences. For example, this string
will turn into this one after your replacement:
This sort of thing is popularly known as the Clbuttic mistake.