Finding the occurrences of a given string and replacing them with the given word.
There are two approaches:
- Using RegEx
We can use Regular expression to this task. Here is the code.
var newPhrase = phrase.replace(/train/g, 'trains')
//Output: Bullet trains are the best. They are among the best Train in the world.
This is case sensitive RegEx. That means, Trains and train is different word.
Here is the case insensitive code.
var newPhrase = phrase.replace(/train/gi, 'trains')
//Output: Bullet trains are the best. They are among the best trains in the world.
Another approach is using split() and join() method.
Here string is first split by the matching word and later we append the string with the replacement word using join() method. This is case sensitive.
Check out the codepen for the live demo.