Main Page

Backreferences

Expressions to match leading and trailing white space are very simple thanks to the
\s
character class
that matches all the white space characters:
var reExtraSpace = /^\s+(.*?)\s+$/;
This regular expression looks for one or more occurrences of white space at the beginning of the string,
followed by any number of additional characters (which are captured in a group), followed by one or
more occurrences of white space at the end of the string. By using this in conjunction with the
String
object’s
replace()
method and backreferences, you can define your own
trim()
method:
String.prototype.trim = function () {
var reExtraSpace = /^\s+(.*?)\s+$/;
return this.replace(reExtraSpace, “$1”);
};
With this method, you can create trimmed versions of strings very easily:
var sTest = “ this is a test “;
alert(“[“ + sTest + “]”); //outputs “ [ this is a test ] “
alert(“[“ + sTest.trim() + “]”); //outputs “ [this is a test]”
Backreferences
So what do you do with groups after the expression has been evaluated? Each group is stored in a spe-
cial location for later use. These special values, stored from your groups, are called
backreferences
.
Backreferences are created and numbered by the order in which opening parenthesis characters are
encountered going from left to right. For example, the expression
(A?(B? (c?)))
creates three back-
references numbered 1 through 3:
1.
(A? (B? (c?)))
2.
(B? (c?))
3.
(c?)
The backreferences can then be used in a couple of different ways.
First, the values of the backreferences can be obtained from the
RegExp
constructor itself by using the
test()
,
match()
, or
search()
methods. For example:
var sToMatch = “#123456789”;
var reNumbers = /#(\d+)/;
reNumbers.test(sToMatch);
alert(RegExp.$1); //outputs “123456789”
This example tries to match the pound sign followed by one or more digits. The digits are grouped so
they will be stored. After the
test()
method is called, all backreferences have been stored on the
RegExp
constructor starting with
RegExp.$1
, which stores the first backreference (it continues with
RegExp.$2
if there is a second,
RegExp.$3
if there is a third, and so on). Because the group matches
“123456789”
, that is what is stored in
RegExp.$1
.
206
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 206


JavaScript EditorFree JavaScript Editor     Ajax Editor


©