The RegExp constructor function has several static properties.
These properties are changed based on the last regular-expression operation performed.
They can be accessed in two different ways:a verbose property name and a shorthand name.
The RegExp constructor properties are listed in the following table.
Verbose Name | Short Name | Description |
---|---|---|
input | $_ | The last string matched against. |
lastMatch | $& | The last matched text. |
lastParen | $+ | The last matched capturing group. |
leftContext | $` | The text that appears in the input string prior to lastMatch. |
multiline | $* | A Boolean value specifying whether all expressions should use multiline mode. |
rightContext | $' | The text that appears in the input string after lastMatch. |
These properties can extract specific information about the operation performed by exec() or test().
Consider this example:
var text = "this test is a test test test"; var pattern = /(.)st/g; if (pattern.test(text)){ console.log(RegExp.input);//input property contains the original string. console.log(RegExp.leftContext); console.log(RegExp.rightContext); console.log(RegExp.lastMatch); console.log(RegExp.lastParen); console.log(RegExp.multiline); } text = "this test is a test test test"; pattern = /(.)st/g;/* w w w. j a v a 2s.c o m*/ if (pattern.test(text)){ console.log(RegExp.$_); console.log(RegExp["$`"]); console.log(RegExp["$'"]); console.log(RegExp["$&"]); console.log(RegExp["$+"]); console.log(RegExp["$*"]); }
Constructor has properties to store up to nine capturing-group matches.
These properties are accessed via RegExp.$1, which contains the first capturing-group match through RegExp.$9, which contains the ninth capturing-group match.
These properties are filled in when calling either exec() or test()
var text = "this test is a test test test"; var pattern = /(..)or(.)/g; if (pattern.test(text)){ console.log(RegExp.$1);/*from w w w . j av a2s .co m*/ console.log(RegExp.$2); console.log(RegExp.$3); }
In this example, a pattern with two matching groups is created and tested against a string.
Even though test() simply returns a Boolean value, the properties $1 and $2 are filled in on the RegExp constructor.