Java Reference
In-Depth Information
In the example, the 7-digit phone number was left unformatted. Suppose that you
want to format a 7-digit phone as
nnn-nnnn
. You can achieve this using a replacement
function as the second argument to the
replace()
method of the
String
object. The
replacement function is called with the following arguments for each match:
•
The number of arguments is the number of groups in the regular
expression plus 3
•
The first argument is the matched text
•
The second and subsequent arguments are the matched text for
the groups, if any, starting at group 1
•
The matched text for the last group is followed by the position in
the input text where the match was found
•
The last argument is the input text itself
The returned value from the replacement function replaces the matched text in the
result returned by the
replace()
method. Listing 4-27 shows how to use a replacement
function to format 7-digit and 10-digit phone numbers. Notice that the first group of three
digits is optional in the pattern. If a group does not match in the matched text, back-
referencing the group returns
undefined
. This logic is used in the
phoneFormatter()
function. If the argument named
group1
is
undefined
, it means that a 7-digit phone
number was matched; otherwise, a 10-digit phone number was matched.
Listing 4-27.
Formatting 7-Digit and 10-Digit Phone Numbers Using a Replacement
Function
// phoneformatter.js
// Formats 10-digit and 7-digit phone numbers
function phoneFormatter(macthedText, group1, group2, group3, startIndex,
inputText) {
if (group1 === undefined) {
// Matched a 7-digit phone number
return group2 + "-" + group3;
}
else {
// Matched a 10-digit phone number
return "(" + group1 + ") " + group2 + "-" + group3;
}
}
// Make the first group of 3-digits optional using the ? metacharacter
var pattern = /\b(\d{3})?(\d{3})(\d{4})\b/g;
var text = "3342449999, 2229822, and 6152534734";
Search WWH ::
Custom Search