1. Home
  2. Computing & Technology
  3. JavaScript

Regular Expressions

20. Properties of RegExp

clr gif

We have already used some of the properties belonging to the RegExp object in previous tutorials. You probably didn't realise that we had though because the way that we have used them is not the way that you would normally expect to reference the property of an object in Javascript. In this tutorial we shall look at all of the properties that are available with a RegExp object and the different ways that you can reference those properties. Regular expressions have two types of properties, the usual sort that exist separately for each object and also a few special static properties that only have one copy exist for all regular expressions. Static properties change each time any regular expression is processed.

Let's begin by revisiting some of the properties that we have already met. The first properties that we were introduced to were "global" and "ignoreCase". These properties were set by our placing a "g" snd/or an"i" after the regular expression or as the second parameter passed when defining a RegExp object. Once we have defined our regular expression we can also access these properties directly using the full property names global and ignoreCase.

var re = /cat/ig;
if (re.global) alert('global is set');

Similarly we can work with multiline mode via the static multiline property. In this case an alternate shorter name for this property also exists - $*. Setting this property will convert all regular expressions to multiline mode at once. Note that not all browsers support this property.

Another group of static properties that we have already met are $1 through $9 which allow access to the backreference array of parenthesized substrings. While no longer forms of these names exist there is one related properties that has both a short and a long name. The static lastParen property references the last parenthesized substring match which can also be referenced using - $+.

As well as being able to reference these static properties within the regular expression processing itself we can also access them at any time following by fully qualifying the references like this:

var re = /(\w)(\w+) (\w)(/w+)/ig;
var myname = 'stePhEn cHaPMan';
myname.match(re);
myname = RegExp.$1.toUpperCase() + RegExp.$2.toLowerCase() + ' ' + RegExp.$3.toUpperCase() + RegExp.$4.toLowerCase();

This code takes each of the backreferenced values extracted from the myname field and applies the correct capitalization to it to convert 'stePhEn cHaPMan' into 'Stephen Chapman'.

Explore JavaScript
About.com Special Features

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

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

All rights reserved.