1. Home
  2. Computing & Technology
  3. JavaScript

Regular Expressions

21. More Properties of RegExp

clr gif

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:

  • "Over the moon."
  • "Over "
  • " moon."
  • "the"
  • "t"
  • "(t)he"

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.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.