Working with text or strings in JavaScript is really interesting. In fact text or “String” as it is called in JavaScript is the most common data type that a JavaScript programmer would encounter quite often. And many a times your would come across scenarios where you might have to replace a text in JavaScript.

Thankfully, JavaScript has many in-built functions that can help you with string or texts. One such function is the replace() function.

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 ! */

Well now you might be wondering why did I put the word John within two forward slashes ( / ) ? That is just because I’m using a regular expression. The using the regular expression, I’m basically telling JavaScript to look for the word John globally or across the sentence (that is done by the g flag) and also to be case-insensitive and ignore if the word John is in capital case or small case (using the i flag)

Hope you found the solution to “How to replace text in JavaScript” you were looking for. Replacing text in JavaScript is easy and interesting at the same time. It is easy because we have a lot of inbuilt functions in JavaScript that help you work with texts or Strings. At the same time it can get tricky in situations like these where there isn’t a direct replaceAll() function in JavaScript for strings and you have to rely on other helping tools in JavaScript like the Regular expression etc.