Now let’s say that I want to replace the Word “John” from the below mentioned text with “Tom”
let myText = "John is happy today as John won the match !"; myText = myText.replace('John','Tom'); // this would replace the variable myText with the text "Tom is happy today as John won the match !"
If you notice, only the first occurrence of the word “John” was replaced and the next occurrence remained intact. Well, unless you are Tom and are John’s best friend, this is not the text you wanted :)
So let’s see how can we replace all occurrences of a text or word in a text or string
let myText = "John is happy today as John won the match !"; myText = myText.replace(/John/gi,'Tom'); // this would replace the variable myText with the text "Tom is happy today as Tom won the match !"