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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/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”!
#javascript #programming