HTML and CSS Reference
In-Depth Information
Figure H-6
Methods of regular expression objects
Method
Description
re
.compile(
pattern,
modifiers
)
compiles or recompiles a regular expression
re
, where
pattern
is the text string of the new regular expression pattern and
modifiers
contains modifiers applied to the
pattern
re
.exec(
string
)
executes a search on
string
using the regular expression
re
;
pattern results are returned in an array and reflected in the
properties of the global
RegExp
object
re
.match(
string
)
performs a pattern match on
string
using the
re
regular expres-
sion; matched substrings are stored in an array
string
.replace
(
re
,
newsubstr
)
replaces the substring defined by the regular expression
re
in the
text string
string
with
newsubstr
string
.search(
re
)
searches
string
for a substring matching the regular expression
re
; returns the index of the match, or -1 if no match is found
string
.split(
re
)
splits
string
at each point indicated by the regular expression
re
;
the substrings are stored in an array
re
.test(
string
)
performs a pattern match on the text string
string
using the regu-
lar expression
re
, returning the Boolean value
true
if a match is
found and
false
otherwise
Validating a Postal Code using Regular Expressions
You can use JavaScript and regular expressions to validate a variety of text patterns. For
example, you may have Web form in which you need to validate a recipient's postal
code. The following function demonstrates how to employ a regular expression that
matches either a five-digit or nine-digit zip code or an empty text string (when the postal
code is not required for delivery). The regular expression is
/^\d{5}(-\d{4})?$|^$/
This regular expression matches zip codes in the form
nnnnn
or
nnnnn-nnnn
; it also
uses the alternation character
|
to allow for empty text strings. You can use this regular
expression in the following function:
function checkZipRE(zip) {
var regx = /^\d{5}(-\d{4})?$|^$/;
return regx.test(zip);
}