Regular Expressions20. 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 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'. |


