↑
Main Page
RegExp.multiline
You can also use the short names for these properties, although you must use the bracket notation for
most of them because some names use illegal ECMAScript syntax:
var sToMatch = “this has been a short, short summer”;
var reShort = /(s)hort/g;
reShort.test(sToMatch);
alert(RegExp.$_); //outputs “this has been a short, short summer”
alert(RegExp[“$`”]); //outputs “this has been a “
alert(RegExp[“$’”]); //outputs “, short summer”
alert(RegExp[“$&”]); //outputs “short”
alert(RegExp[“$+”]); //outputs “s”
Keep in mind that every time
exec()
or
test()
is called, all these properties (except
multiline
) are
reset. Example:
var sToMatch1 = “this has been a short, short summer”;
var sToMatch2 = “this has been a long, long summer”;
var reShort = /(s)hort/g;
var reLong = /(l)ong/g;
reShort.test(sToMatch1);
alert(RegExp.$_); //outputs “this has been a short, short summer”
alert(RegExp[“$`”]); //outputs “this has been a “
alert(RegExp[“$’”]); //outputs “, short summer”
alert(RegExp[“$&”]); //outputs “short”
alert(RegExp[“$+”]); //outputs “s”
reLong.test(sToMatch1);
alert(RegExp.$_); //outputs “this has been a long, long summer”
alert(RegExp[“$`”]); //outputs “this has been a “
alert(RegExp[“$’”]); //outputs “, long summer”
alert(RegExp[“$&”]); //outputs “long”
alert(RegExp[“$+”]); //outputs “l”
Here, a second regular expression,
reLong
, is used after
reShort
. All the
RegExp
properties are set to
new values.
The
multiline
property is a different type of property because it doesn’t depend on the last executed
match. Instead, it sets the
m
option for every regular expression in scope:
var sToMatch = “First second\nthird fourth\nfifth sixth”
var reLastWordOnLine = /(\w+)$/g;
RegExp.multiline = true;
var arrWords = sToMatch.match(reLastWordOnLine);
When this code completes execution,
arrWords
contains
“second”
,
“fourth”
, and
“sixth”
, just as if
the
m
option is used in the regular expression.
Internet Explorer and Opera don’t support
RegExp.multiline
, so it’s best to use the
m
setting on individual expressions instead of trying to set this flag globally.
215
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 215
Free JavaScript Editor
Ajax Editor
©
→