Java Reference
In-Depth Information
chocoholic
sugar candy
candy
Let's examine the regular expression to remove the offending words.
1.
Start with the two basic words, so to match “choc” or “candy,” you use
candy|choc
2.
Add the matching for “sugar candy.” Since the “sugar” bit is optional, you group it by placing it
in parentheses and adding the “?” after it. This means match the group zero times or one time.
(sugar )?candy|choc
3.
You need to add the optional “olate” and “oholic” end bits. You add these as a group after the
“choc” word and again make the group optional. You can match either of the endings in the
group by using the | character.
(sugar )?candy|choc(olate|oholic)?/gi
4.
You, then, declare it as
var myRegExp = /(sugar )?candy|choc(olate|oholic)?/gi
The gi at the end means the regular expression will fi nd and replace words on a global, case-insensitive
basis.
So, to sum up
/(sugar )?candy|choc(olate|oholic)?/gi
reads as:
Either match zero or one occurrences of “sugar” followed by “candy.” Or alternatively match “choc”
followed by either one or zero occurrences of “olate” or match “choc” followed by zero or one occur-
rence of “oholic.”
Finally, the following:
myString = myString.replace(myRegExp,”salad”);
replaces the offending words with “salad” and sets myString to the new clean version:
“Mmm, I love salad, I'm a salad. I love salad too, sweet, salad.”
Search WWH ::




Custom Search