Regular Expressions21. More Properties of RegExp |
|
Join the DiscussionMore of this FeatureIntroduction Pattern Matching Ignore Case and Global Replacing Matches Spliting Matches Start and End Meta Characters Character Classes Repetitions Greedy, Reluctant, etc. Predefined Classes Special Characters ASCII and Unicode Boundaries Grouping Back References Non-Capturing Groups Lookahead Multiline Mode The RegExp Object Properties of RegExp We'll now move on to consider some more of the properties that we haven't referenced before. Unless a regular expression is testing for start of field, end of field, or both, a regular expression effectively breaks up the text being searched into three pieces - the part before the matched text, the matched text itself, and the part after the matched text. Each of these three parts for the last match that was performed can be accessed via static RegExp properties - leftContext or $` contains whatever precedes the match, lastMatch or $& contains the matched content itself, and rightContext or $' contains whatever follows the match. A RegExp object also keeps track of where it is up to with matching the text using the lastIndex property. All regular expression processing involves matching the regular expression itself against some other text and both of these are also able to be accessed via properties. The source property provides access to the regular expression text itself while the static input or $_ property contains the complete text that was processed by the last match. Here is some code that shows how you might reference these properties. Note the difference between the way that normal properties and static properties are referenced.
var re = /(t)he/g;
var mystring = "Over the moon."; re.text(mystring); alert(RegExp.input); // or RegExp.$_ alert(RegExp.leftContext); // or RegExp["$`"] alert(RegExp.rightContext); // or RegExp["$'"] alert(RegExp.lastMatch); // or RegExp["$&"] alert(RegExp.lastParen); // or RegExp["$+"] alert(re.source); If you are wondering what this code would do, it should produce the following alerts one after the other:
Finally, like all Javascript objects, RegExp objects has a constructor property that specifies the function that creates a RegExp and a prototype property that allows additional properties to be added to all RegExp objects at the same time. |

