Java Reference
In-Depth Information
The sentence should become:
“the dog walked in off the street and ordered the finest beer”
exercise 2 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6: Question 2</title>
</head>
<body>
<script>
var myString = "a dog walked in off a street and " +
"ordered a finest beer";
var myRegExp = /\ba\b/gi;
myString = myString.replace(myRegExp, "the");
alert(myString);
</script>
</body>
</html>
Save this as ch6 _ question2.html .
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 first parameter:
myString = myString.replace(myRegExp,"the");
exercise 3 Question
Imagine you have a website 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>
<html lang="en">
Search WWH ::




Custom Search