HTML and CSS Reference
In-Depth Information
Regular Expressions
and Pattern
17.1 What Is a Regular Expression?
A user is asked to fill out an HTML form and provide his or her name, address, and birth
date. Before sending the form off to a server for further processing, a JavaScript program
checks the form to make sure the user actually entered something, and that the infor-
mation is in the requested format. We saw in Chapter 11, “Working with Forms and
Input Devices,” some basic ways that JavaScript can check form information, but now
with the addition of regular expressions, form validation can be much more sophisti-
cated and precise. Regular expressions are also useful for searching for patterns in input
data, and replacing the data with something else or splitting it up into substrings. This
chapter is divided into two main parts: (1.) how to create regular expressions and regu-
lar expression metacharacters, and (2.) how to validate form input data with regular
expressions. If you are savvy with Perl regular expressions (or the UNIX utilities, grep ,
sed, and awk ), you can move rapidly through the first section, because JavaScript regular
expressions, for the most part, are identical to those found in Perl.
A regular expression is really just a sequence of characters that specify a pattern to be
matched against a string of text when performing searches and replacements. A simple
regular expression consists of a character or set of characters that matches itself. The
regular expression is normally delimited by forward slashes; for example, /abc/ .
Like Perl, JavaScript 1 provides a large variety of regular expression metacharacters to
control the way a pattern is found. A metacharacter is a special character that represents
something other than itself, such a a ^, $,*, and so on. They are placed within in the reg-
ular expression to control the search pattern; for example, /^abc/ means look for the pat-
tern abc at the beginning of the line. With the help of metacharacters, you can look for
strings containing only digits, only alphas, a digit at the beginning of the line followed
by any number of alphas, a line ending with a digit, and so on. When searching for a
pattern of characters, the possibilities of fine-tuning your search are endless.
1. JavaScript 1.2, NES 3.0 JavaScript 1.3 added toSource() method. JavaScript 1.5, NES 6.0 added m flag,
nongreedy modifier, noncapturing parentheses, look-ahead assertions. ECMA 262, Edition 3.
Search WWH ::

Custom Search