The RegExp constructor function has several properties.
These are like static properties in other languages.
These properties apply to all regular expressions in scope.
They change based on the last regular-expression operation performed.
RegExp constructor properties can be accessed in two different ways.
Each property has 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 . |
rightContext | $' | The text that appears in the input string after lastMatch . |
These properties can be used to extract specific information about the operation performed by exec()
or test()
.
Consider this example:
let text = "cat fat pat nat test test"; let pattern = /(.)at/g; if (pattern.test(text)) { console.log(RegExp.input); /*from ww w . j ava2s .co m*/ console.log(RegExp.leftContext); console.log(RegExp.rightContext); console.log(RegExp.lastMatch); console.log(RegExp.lastParen); }
These verbose property names can be replaced with the short property names.
let text = "cat fat pat nat test test"; let pattern = /(.)at/g; if (pattern.test(text)) { console.log(RegExp.$_); // ww w.ja va 2s.c om console.log(RegExp["$`"]); console.log(RegExp["$'"]); console.log(RegExp["$&"]); console.log(RegExp["$+"]); console.log(RegExp["$*"]); }
There are constructor properties that store up to nine capturing-group matches.
These properties are accessed via RegExp.$1 through RegExp.$9.
RegExp.$1 contains the first capturing-group match.
RegExp.$9 contains the ninth capturing-group match.
These properties are filled in when calling either exec()
or test()
let text = "this is a test"; let pattern = /(..)or(.)/g; if (pattern.test(text)) { console.log(RegExp.$1); // w w w . jav a2 s .c om console.log(RegExp.$2); }