HTML and CSS Reference
In-Depth Information
Another useful technique in regular expressions is to group character symbols. Once
you create a group, the symbols within that group can be treated as a single unit. The
syntax to create a group is
(
pattern
)
where
pattern
is a regular expression pattern. For example, a phone number might be
entered with or without an area code. The pattern for a phone number without an area
code, matching such numbers as
555-1234
, is
/^\d{3}-\d{4}$/
If an area code is included in the format
800-555-1234
, the pattern is
/^\d{3}-\d{3}-\d{4}$/
To allow the area code to be added, you place it within a group and use the
?
repetition
character applied to the entire area code group. The regular expression is thus
/^(\d{3}-)?\d{3}-\d{4}$/
which matches either
555-1234
or
800-555-1234
.
Working with the Regular Expression Object
Now that you have reviewed the syntax involved in writing a regular expression, you can
use regular expressions in JavaScript programs. As noted earlier, a regular expression is
treated as an object with its own collection of properties and methods.
Exploring Regular Expression Methods
One method associated with regular expressions is the
test()
method, which is used to
determine whether a text string contains a substring that matches the pattern defined by a
regular expression. The syntax of the
test()
method is
re
.test(
string
)
where
re
is a regular expression object and
string
is the text string you want to test.
The
test()
method returns the Boolean value
true
if a match is located within the text
string and
false
otherwise. For example, the following code uses the
test()
method to
compare the text string stored in the
zipstring
variable with the regular expression object
stored in the regx variable:
var zipstring = document.forms[0].zip.value;
var regx = /^\d{5}$/;
var testvalue = regx.test(zipstring);
If
zipstring
matches the pattern, the
testvalue
variable will have a value of
true
; other-
wise, it will have a value of false. If you need to know where within the text string the
match occurs, you can use the following search() method:
re
.search(
string
)
The
search()
method returns the index of the first matching substring from
string
. If
no match is found, it returns the value -1. All searches occur from the start of the text
string.
You can also use regular expression methods that extract substrings from a text string.
The
match()
method creates an array of substrings from a text string that match the pat-
tern defined in a regular expression. The syntax of the match() method is
results = re
.match(
string
)