Main Page

Extended string methods

In this code,
arrMatches
contains three items: the
“at”
from
“bat”
,
“Cat”
, and
“cat”
. To return all
instances of
at
, regardless of the case, just add the
i
option:
var sToMatch = “a bat, a Cat, a fAt baT, a faT cat”;
var reAt = /at/gi;
var arrMatches = reAt.exec(sToMatch);
Now
arrMatches
contains all of the instances of
“at”
, regardless of position or case. Note that the
instances of
“at”
with uppercase letters will be stored in
arrMatches
the same way that they appear
in
sToMatch
. Here are the contents of the
arrMatches
array after this code executes:
Index
Value
From
0
“at”
“bat”
1
“at”
“Cat”
2
“At”
“fAt”
3
“aT”
“baT”
4
“aT”
“faT”
5
“at”
“cat”
The
String
object has a method called
match()
, which intentionally mirrors the functionality of the
RegExp
object’s
exec()
method. The main difference is that the method is called on the
String
object
and the
RegExp
object is passed in as an argument:
var sToMatch = “a bat, a Cat, a fAt baT, a faT cat”;
var reAt = /at/gi;
var arrMatches = sToMatch.match(reAt);
This code yields the same result as the previous example, with
arrMatches
containing all the same
items.
A String method calls
search()
that acts the same way as
indexOf()
, but uses a
RegExp
object instead
of a substring. The
search()
method returns the index of the first occurrence in the string:
var sToMatch = “a bat, a Cat, a fAt baT, a faT cat”;
var reAt = /at/gi;
alert(sToMatch.search(reAt)); //outputs “3”
In this example, the alert will display
“3”
, because the first occurrence of
“at”
is at position 3 in the
string. Specifying the regular expression as global (with the
g
) has no effect when using
search()
.
Extended string methods
Two String methods, discussed earlier in the book, also accept regular expressions as parameters. The
first is the
replace()
method, which replaces all occurrences of a substring (the first argument) with a
different string (the second argument). For example:
195
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 195


JavaScript EditorFree JavaScript Editor     Ajax Editor


©