Java Reference
In-Depth Information
<head>
<title>Chapter 6: Question 3</title>
</head>
<body>
<script>
var myRegExp = /(sugar )?candy|choc(olate|oholic)?/gi;
var myString = "Mmm, I love chocolate, I'm a chocoholic. " +
"I love candy too, sweet, sugar candy";
myString = myString.replace(myRegExp,"salad");
alert(myString);
</script>
</body>
</html>
Save this as ch6 _ question3.html .
For this example, pretend you're creating script for a board on a dieting site where text relating to
candy is barred and will be replaced with a much healthier option, salad.
The barred words are
chocolate
choc
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.” Because 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 find and replace words on a global, case‐
insensitive basis.
Search WWH ::




Custom Search