HTML and CSS Reference
In-Depth Information
A ppendix H
Understanding
Regular
Expressions
Introducing Regular Expressions
A regular expression is a text string that defines a character pat-
tern. One use of regular expressions is pattern matching , in which
a text string is tested to see whether it matches the pattern defined
by a regular expression. For example, with extended postal codes or
zip codes you might create a regular expression that describes the
pattern of five digits followed by a hyphen and another four digits.
Pattern matching is just one use of regular expressions. They can also
be used to extract substrings, insert new text, or replace old text.
The greatest advantage of regular expressions is that the code is
compact and powerful, so that what might take several lines of code
using other text string methods can be done in a single line with a
regular expression. However, with this power comes complexity: the
syntax of regular expressions can be intimidating to new programmers,
taking time and practice to master.
Creating a Regular Expression
You create a regular expression object in JavaScript using the
command
re = /pattern/modifiers;
where re is the variable that stores the regular expression object,
pattern is the text string of the regular expression and modifiers
defines how the regular expression pattern should be applied. This
format for creating a regular expression object is referred to as a
regular expression literal. A regular expression object can also be
created using the following new object constructor:
re = new RegExp( pattern , modifiers )
where re , pattern , and modifiers have the same meanings as
they do with the regular expression literal form. The following two
commands are equivalent as far as JavaScript is concerned:
var reObj = /\b\w+\b/g;
var reObj = new RegExp(“\b\w+\b”,”g”);
StArting dAtA FileS
There are no starting Data Files needed for this appendix.
HTML H1
 
Search WWH ::




Custom Search