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."
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."
So what’s happening in the code?
- First, we declare a new variable called
- Then we set that new variable equal to the value of the original
- Then we attach the
textBlock, and give it an argument of this regular expression:
/Glorious/g, "Epic"which is where the magic happens.
g (global) flag is what allows us to replace all instances of "Glorious" with "Epic" in the text block. The