20. Properties of RegExp
Join the Discussion
More of this Feature
Introduction 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
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 = 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'.