Main Page


You can also include backreferences in the expression that defines the groups. You do this by using the
special escape sequences
, and so on. For example:
var sToMatch = “dogdog”;
var reDogDog = /(dog)\1/;
alert(reDogDog.test(sToMatch)); //outputs “true”
The regular expression
creates a group for the word
, which is then referenced by the spe-
cial escape sequence
, effectively making the regular expression equal to
Third, backreferences can be used with the
method by using the special character
, and so on. The best example to illustrate this functionality is to reverse the order of
two items in a string. Suppose you want to change the string
“1234 5678”
“5678 1234”
. The fol-
lowing code accomplishes this:
var sToChange = “1234 5678”;
var reMatch = /(\d{4}) (\d{4})/;
var sNew = sToChange.replace(reMatch, “$2 $1”);
alert(sNew); //outputs “5678 1234”
In this example, the regular expression has two groups each with four digits. In the second argument of
is equal to
is equal to
, corresponding to the order in
which they appear in the expression.
Sometimes it gets very difficult to create a pattern that correctly matches all the possibilities you have in
mind. What if you need to match
with the same expression? These words have no
characters in common, so you could write two different regular expressions and test a string against
both, like this:
var sToMatch1 = “red”;
var sToMatch2 = “black”;
var reRed = /red/;
var reBlack = /black/;
alert(reRed.test(sToMatch1) || reBlack.test(sToMatch1)); //outputs “true”
alert(reRed.test(sToMatch2) || reBlack.test(sToMatch2)); //outputs “true”
This gets the job done, but it is a little too verbose. The other option is to use the regular expression alter-
nation operator.
The alternation operator is the same as the ECMAScript bitwise OR, a pipe (
), and it is placed between
two independent patterns, as in this example:
var sToMatch1 = “red”;
var sToMatch2 = “black”;
var reRedOrBlack = /(red|black)/;
alert(reRedOrBlack.test(sToMatch1)); //outputs “true”
alert(reRedOrBlack.test(sToMatch2)); //outputs “true”
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 207

JavaScript EditorFree JavaScript Editor     Ajax Editor