Main Page

Alternation

You can also include backreferences in the expression that defines the groups. You do this by using the
special escape sequences
\1
,
\2
, and so on. For example:
var sToMatch = “dogdog”;
var reDogDog = /(dog)\1/;
alert(reDogDog.test(sToMatch)); //outputs “true”
The regular expression
reDogDog
creates a group for the word
dog
, which is then referenced by the spe-
cial escape sequence
\1
, effectively making the regular expression equal to
/dogdog/
.
Third, backreferences can be used with the
String
’s
replace()
method by using the special character
sequences
$1
,
$2
, 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”
to
“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
the
replace()
method,
$2
is equal to
“5678”
and
$1
is equal to
“1234”
, corresponding to the order in
which they appear in the expression.
Alternation
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
“red”
and
“black”
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”
207
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 207


JavaScript EditorFree JavaScript Editor     Ajax Editor


©