Main Page

Using a RegExp object

This regular expression matches only the first occurrence of the word
“cat”
in a string, and it is case-
sensitive. To make the regular expression match all occurrences of
“cat”
, you can add the second argu-
ment to the constructor:
var reCat = new RegExp(“cat”, “g”);
In this line, the second argument
“g”
is short for
global
, meaning that the entire string is searching for
occurrences of
“cat”
instead of stopping after the first occurrence. If you want to make the pattern
case-insensitive, you can add the character
“i”
to the second argument (
“i”
is short for
insensitive
, as
in
case-insensitive
):
var reCat = new RegExp(“cat”, “gi”);
Some regular expression literals use Perl-style syntax:
var reCat = /cat/gi;
Regular expression literals begin with a forward slash, followed by the string pattern, followed by
another forward slash. If you want to specify additional processing instructions, such as
“g”
and
“i”
,
these come after the second forward slash (as in the previous example).
Using a RegExp object
After creating a
RegExp
object, you apply it to a string. You can use several methods of both
RegExp
and
String
.
The first thing you do with a regular expression is determine if a string matches the specified pattern.
For this simple case, the
RegExp
object has a method called
test()
, which simply returns
true
if the
given string (the only argument) matches the pattern and
false
if not:
var sToMatch = “cat”;
var reCat = /cat/;
alert(reCat.test(sToMatch)); //outputs “true”
In this example, the alert outputs
“true”
because the pattern matches the string. Even if the pattern
only occurs once in the string, it is considered a match, and
test()
returns
true
. But what if you want
access to the occurrences of the pattern? For this use case, you can use the
exec()
method.
The
RegExp exec()
method, which takes a string as an argument, returns an
Array
containing all
matches. Consider the following example:
var sToMatch = “a bat, a Cat, a fAt baT, a faT cat”;
var reAt = /at/;
var arrMatches = reAt.exec(sToMatch);
Here,
arrMatches
contains only one item: the first instance of
“at”
(which is in the word
“bat”
).
If you want to return all instances of
“at”
, add the
g
option:
var sToMatch = “a bat, a Cat, a fAt baT, a faT cat”;
var reAt = /at/g;
var arrMatches = reAt.exec(sToMatch);
194
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 194


JavaScript EditorFree JavaScript Editor     Ajax Editor


©