Replacing multiple instances of a string inside another string in JavaScript
Let’s say we have a variable, text
, assigned to a string
:
let text = "the cat sat on the mat";
We want to replace the word “the” with the word “no”.
A JavaScript string
has a nice replace
method that we can use to do this. So, let’s give this a try:
text = text.replace("the", "no");
The text
variable now contains the value “no cat sat on the mat”. This perhaps isn’t what we’d hoped for - only the first “the” has been replaced.
The first, parameter in the replace
method can actually be a regular expression which we can use to specify that we want to replace all the instances of the matched word:
text = text.replace(/the/g, "no");
The g
at the end of the regular expression tells the replace
method to match all instances.
So, the text
variable now contains the value “no cat sat on no mat”. Great - we managed to replace all the instances of “the” with “no”!
Let’s look at a slightly different example now:
let text = "The cat sat on the mat";
Again, we want to replace all the instances of the word “the” with “no”. However, this time the two instances of “the” are in different cases - “The” and “the”.
So, just doing the following:
text = text.replace(/the/g, "no");
… will give us “The cat sat on no mat”.
Not quite what we wanted!
The solution is simple though:
text = text.replace(/the/gi, "no");
We have extended the regular expression and specified a case insensitive match with i
.
So, the text
variable now contains the value “no cat sat on no mat”.
Nice!
Below is a working example in CodePen: