Java Reference
In-Depth Information
Summary
In this chapter you've looked at some more advanced methods of the String object and how you can
optimize their use with regular expressions.
To recap, the chapter covered the following points:
The
split() method splits a single string into an array of strings. You pass a string or a regular
expression to the method that determines where the split occurs.
The
replace() method enables you to replace a pattern of characters with another pattern that
you specify as a second parameter.
The
search() method returns the character position of the fi rst pattern matching the one given
as a parameter.
The
match() method matches patterns, returning the text of the matches in an array.
Regular expressions enable you to defi ne a pattern of characters that you want to match. Using
this pattern, you can perform splits, searches, text replacement, and matches on strings.
In JavaScript the regular expressions are in the form of a
RegExp object. You can create
a RegExp object using either myRegExp = /myRegularExpression/ or myRegExp = new
RegExp(“myRegularExpression”). The second form requires that certain special characters
that normally have a single \ in front now have two.
The
g and i characters at the end of a regular expression (as in, for example, myRegExp =
/Pattern/gi;) ensure that a global and case-insensitive match is made.
As well as specifying actual characters, regular expressions have certain groups of special char-
acters, which allow any of certain groups of characters, such as digits, words, or non-word
characters, to be matched.
Special characters can also be used to specify pattern or character repetition. Additionally, you
can specify what the pattern boundaries must be, for example at the beginning or end of the
string, or next to a word or non-word boundary.
Finally, you can defi ne groups of characters that can be used later in the regular expression or in
the results of using the expression with the replace() method.
In the next chapter, you'll take a look at using and manipulating dates and times using JavaScript, and
time conversion between different world time zones. Also covered is how to create a timer that executes
code at regular intervals after the page is loaded.
Exercise Questions
Suggested solutions to these questions can be found in Appendix A.
1.
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”);
Search WWH ::




Custom Search