Main Page

reRedOrBlack

In this,
reRedOrBlack
matches either
“red”
or
“black”
, and testing against each string yields
“true”
.
Because the alternation is contained in a group, whichever alternative is matched is stored in
RegExp.$1
for later use (as well as being available as
\1
in the expression). In the first test,
RegExp.$1
is equal to
“red”
; in the second, it is equal to
“blue”
.
You can specify as many options as you’d like just by adding more alternatives and more alternation
operators:
var sToMatch1 = “red”;
var sToMatch2 = “black”;
var sToMatch3 = “green”;
var reRedOrBlack = /(red|black|green)/;
alert(reRedOrBlack.test(sToMatch1)); //outputs “true”
alert(reRedOrBlack.test(sToMatch2)); //outputs “true”
alert(reRedOrBlack.test(sToMatch3)); //outputs “true”
A more practical use of an OR pattern is to remove inappropriate words from user input, which can be
very important in online forums. By using an OR pattern with the inappropriate words and the
replace()
method, you can easily strip out any offensive material before it is posted:
var reBadWords = /badword|anotherbadword/gi;
var sUserInput = “This is a string using badword1 and badword2.”;
var sFinalText = sUserInput.replace(reBadWords, “****”);
alert(sFinalText); //output “This is a string using **** and ****”
This example specifies
“badword1”
and
“badword2”
to be inappropriate. The expression
reBadWords
uses the OR operator to specify both words (note that both the global and case-insensitive flags are set).
When the
replace()
method is used, each of the inappropriate words is replaced with four asterisks
(the proverbial four-letter word representation).
You can also replace inappropriate words using an asterisk to replace each letter, meaning that the
replacement text contains the same number of characters as the word in question. This can be done
using a function as the second argument to the
replace()
method:
var reBadWords = /badword|anotherbadword/gi;
var sUserInput = “This is a string using badword1 and badword2.”;
var sFinalText = sUserInput.replace(reBadWords, function(sMatch) {
return sMatch.replace(/./g, “*”);
});
alert(sFinalText); //output “This is a string using ******* and **************”
In this code, the function passed in as the second argument to
replace()
actually uses another regular
expression. When the function is executed,
sMatch
contains one of the inappropriate words. The fastest
way to replace each character with an asterisk is to use the
replace()
method on
sMatch
, specifying a
pattern that matches any character (the period) and replacing it with an asterisk (note that the global flag
has been set as well). Techniques such as this can ensure that inappropriate remarks cannot get posted to
your online forum or bulletin board.
208
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 208


JavaScript EditorFree JavaScript Editor     Ajax Editor


©