Main Page

Regular Expressions

Regular Expressions
Once upon a time, testing for patterns contained within strings was an arduous process. It often
involved using string functions such as
charAt()
and
indexOf()
. Languages such as Perl imple-
mented a solution called regular expressions based on a Unix administration tools such as gred
and ed.
Regular expressions are strings with a special syntax indicating the occurrence of specific characters
or substrings within another string. These patterns range from very simple to very complicated and
can be used to do anything from removing white space to validating credit card numbers.
JavaScript has natively supported regular expressions for longer than some high-powered lan-
guages, such as Java, which only introduced native regular expression support in JDK 1.4. Entire
books are written on the subject of regular expressions because they can be very complicated; this
chapter looks specifically at how JavaScript implements regular expressions
Regular Expression Support
JavaScript supports regular expressions through the ECMAScript
RegExp
class. The constructor for
a
RegExp
object takes one or two arguments. The first (or only) argument is the string describing
the pattern to match; if there is a second argument, it is a string specifying additional processing
instructions.
The most basic regular expression is a regular string. For instance, to match the word
“cat”
, you
can define the regular expression like this:
var reCat = new RegExp(“cat”);
10_579088 ch07.qxd 3/28/05 11:38 AM Page 193


JavaScript EditorFree JavaScript Editor     Ajax Editor


©