Java Reference
In-Depth Information
<p>
It includes a guide to the language - when where and how to get
the most out of JavaScript - together with practical case studies
demonstrating JavaScript in action. Coverage is bang up-to-date, with
discussion of compatability issues and version differences, and the
book concludes with a comprehensive reference section.
</p>
</body>
</html>
Chapter 9
Exercise 1 Question
What problem does the following code solve?
var myString = “This sentence has has a fault and and we need to fix it.”
var myRegExp = /(\b\w+\b) \1/g;
myString = myString.replace(myRegExp,”$1”);
Now imagine that you change that code, so that you create the RegExp object like this:
var myRegExp = new RegExp(“(\b\w+\b) \1”);
Why would this not work, and how could you rectify the problem?
Exercise 1 Solution
The problem is that the sentence has “has has” and “and and” inside it, clearly a mistake. A lot of word
processors have an autocorrect feature that fi xes common mistakes like this, and what your regular
expression does is mimic this feature.
So the erroneous myString
“This sentence has has a fault and and we need to fi x it.”
will become
“This sentence has a fault and we need to fi x it.”
Let's look at how the code works, starting with the regular expression.
/(\b\w+\b) \1/g;
By using parentheses, you have defi ned a group, so (\b\w+\b) is group 1 . This group matches the pat-
tern of a word boundary followed by one or more alphanumeric characters, that is, a-z, A-Z, 0-9, and _,
followed by a word boundary. Following the group you have a space then \1 . What \1 means is match
Search WWH ::




Custom Search