Java Reference
In-Depth Information
With regular expressions, it's often not just what you want to match, but also what you don't want to
match that is a problem. Here you want to match the letter a, so why not just write
var myRegExp = /a/gi;
Well, that would work, but it would also replace the “a” in “walked,” which you don't want. You want to
replace the letter “a” but only where it's a word on its own and not inside another word. So when does
a letter become a word? The answer is when it's between two word boundaries. The word boundary is
represented by the regular expression special character \b so the regular expression becomes
var myRegExp = /\ba\b/gi;
The gi at the end ensures a global, case-insensitive search.
Now with your regular expression created, you can use it in the replace() method's fi rst parameter.
myString = myString.replace(myRegExp,”the”);
Exercise 3 Question
Imagine you have a web site with a message board. Write a regular expression that would remove
barred words. (You can make up your own words!)
Exercise 3 Solution
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script language=”JavaScript” type=”text/javascript”>
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 ch09_q3.htm.
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
Search WWH ::




Custom Search