↑
Main Page
Static properties
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “1”
reB.lastIndex = 0;
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “1”
With the change in this code, both calls to
exec()
find the
b
in position 0, so both times, the alert dis-
plays
“1”
as the value of
lastIndex
.
Static properties
The static
RegExp
properties apply to all regular expressions in scope. These properties are also unique
because they each have two names: a verbose name and a short name beginning with a dollar sign. The
properties are listed in the following table.
Verbose Name
Short Name Description
input
$_
The last string matched against (the string passed in
to
exec()
or
test()
)
lastMatch
$&
The last matched characters
lastParen
$+
The last matched group
leftContext
$`
The substring before the last match
multiline
$*
A Boolean value specifying whether all expressions
should use multiline mode
rightContext
$’
The substring after the last match
These properties can be used to tell you specific information about the match just completed using
exec()
or
test()
. Example:
var sToMatch = “this has been a short, short summer”;
var reShort = /(s)hort/g;
reS.test(sToMatch);
alert(RegExp.input); //outputs “this has been a short, short summer”
alert(RegExp.leftContext); //outputs “this has been a “
alert(RegExp.rightContext); //outputs “, short summer”
alert(RegExp.lastMatch); //outputs “short”
alert(RegExp.lastParen); //outputs “s”
This example illustrates how the various properties are used:
?
The
input
property is always equal to the string being tested.
?
RegExp.leftContext
contains everything before the first instance of
“short”
and
RegExp.rightContext
contains everything after the first instance of
“short”
.
?
The
lastMatch
property contains the last string that matches the entire regular expression,
which is
“short”
.
?
The
lastParen
property contains the last matched group, which in this case is
“s”
.
214
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 214
Free JavaScript Editor
Ajax Editor
©
→