↑
Main Page
Instance properties
already been discussed in this chapter. But the
RegExp
object also has properties, both on the constructor
and on instances of
RegExp
. Both sets of properties change as patterns are created and tested.
Instance properties
An instance of
RegExp
has a number of properties that can be of use to developers:
?
global
— A Boolean value indicating whether or not the
g
option has been set
?
ignoreCase
— A Boolean value indicating whether or not the
i
option has been set
?
lastIndex
— An integer representing the character position where the next match will be
attempted (only filled after using
exec()
or
test()
, otherwise is 0)
?
multiline
— A Boolean value indicating whether the
m
option has been set
?
source
— The string source of the regular expression. For example, the expression
/[ba]*/
returns
“[ba]*”
as its
source
.
You don’t typically use the
global
,
ignoreCase
,
multiline
, and
source
properties because you often
already have the data they provide:
var reTest = /[ba]*/i;
alert(reTest.global); //outputs “false”
alert(reTest.ignoreCase); //outputs “true”
alert(reTest.multiline); //outputs “false”
alert(reTest.source); //outputs “[ba]*”
The really useful property is
lastIndex
, which tells you how far the regular expression has traveled
along a string before stopping:
var sToMatch = “bbq is short for barbecue”;
var reB = /b/g;
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “1”
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “2”
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “18”
reB.exec(sToMatch);
alert(reB.lastIndex); //outputs “21”
In this example, the regular expression
reB
is looking for the character
b
. When it is first executed
against
sToMatch
, it finds the
b
in the first position, position 0; therefore, the
lastIndex
property is set
to 1, which is where the matching picks up when
exec()
is called again. When it’s called again, the
expression finds the
b
in position 1, which sets
lastIndex
to 2. When called a third time, it finds the
b
in position 17, setting
lastIndex
to 18, and so on.
If you want the matching to start at the beginning again, you can always set
lastIndex
to 0:
var sToMatch = “bbq is short for barbecue”;
var reB = /b/g;
213
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 213
Free JavaScript Editor
Ajax Editor
©
→