Learn how to replace all instances of a word (string) in JavaScript by using regular expressions (RegEx) and the replace()
method.
Let’s say you have a huge block of text that talks about your company’s latest product, but unfortunately, one word was misspelled multiple times. The following text block was supposed to say “Epic Games” not “Glorious Games”:
const textBlock =
"We at Glorious Games, are very proud to present the latest edition of the Unreal Tournament series. Glorious Games would like to invite our fans to come over to the Glorious Games stand at E3 in 2021."
Fortunately, we can fix this with JavaScript fast.
const textBlockCorrected = textBlock.replace(/Glorious/g, "Epic")
console.log(textBlockCorrected)
// "We at Epic Games, are very proud to present the latest edition of the Unreal Tournament series. Epic Games would like to invite our fans to come over to the Epic Games stand at E3 in 2021."
Yay!
So what’s happening in the code?
- First, we declare a new variable called
textBlockCorrected
. - Then we set that new variable equal to the value of the original
textBlock
. - Then we attach the
replace()
method totextBlock
, and give it an argument of this regular expression:/Glorious/g, "Epic"
which is where the magic happens.
The g
(global) flag is what allows us to replace all instances of "Glorious" with "Epic" in the text block. The g
flag is the only way to replace multiple instances of a word in a string, in JavaScript.