RegExp instance
The RegExp instance has certain properties that are added to each instance by default. These properties are:
- global; a Boolean value that indicates if the g modifier has been set;
- ignoreCase; a Boolean value that indicates if the i modifier has been set;
- lastIndex; an integer value that indicates the index (position) of a character at which the next match is going to start ("0" refers to the first character);
- multiline; a Boolean value that indicates if the m modifier has been set;
- source; a string value that contains the pattern (text) of the regular expression (in its literal form).
The following example shows how some of these properties work:
var pattern = /[ab]/i;
alert(pattern.ignoreCase); //true
alert(pattern.source); //"[ab]"
Although useful in troubleshooting, these properties are not very often used concerning that the information needed already exists in the pattern itself.
RegExp constructor
Beside instances of a RegExp type, the RegExp constructor has certain default properties as well. These properties apply to all regular expressions that are in scope of the RegExp constructor being executed.
These are properties are:
Name | Abbr. | Description |
---|---|---|
input | $_ | shows the last string matched against |
lastMatch | $& | shows the last matched text |
lastParen | $+ | shows the last matched capturing group |
leftContext | $' | shows the text that appears in the input string before the lastMatch |
multiline | $* | indicates (as Boolean) if all expressions should use multiline mode |
rightContext | $` | shows the text that appears in the input string after the lastMatch |
These properties may be used in combination with RegExp methods (see next chapter) to extract specific information about the operation done by those methods. For instance:
var text = "Hello, my name is Tony Bravo";
var pattern = /(.)ony/g;
if (pattern.test(text)) {
alert(RegExp.input); //"Hello, my name is Tony"
alert(RegExp.leftContext); //"Hello, my name is "
alert(RegExp.rightContext); //" Bravo"
alert(RegExp.lastMatch); //"Tony"
alert(RegExp.lastParen); //"T"
alert(RegExp.multiline); //false
}
The property names may be replaced with the short names (2nd column in the table above) but it might not work well in all the browsers.
If multiple groups matching per expression is required, the lastParen property may be replaced with $1 to $9 numerical short named groups, with $1 referring to the first match, $2 to the second, etc... Applying that to the example from above, it would look something like that:
var text = "Hello, my name is Nicholas Bravo";
var pattern = /(..)chola(.)/g;
if (pattern.test(text)) {
alert(RegExp.$1); //Ni
alert(RegExp.$2); //s
}
Example
Example of a basic usage of RegExp properties in JavaScript:
Comments
No comments have been made yet.
Please login to leave a comment. Login now