They're Handy for Searching, Don't You Know?
To those who maintain connections with the world outside of computer
programming, the term "regular expression" is funny. On my shelf, I
have a copy of Jeffrey Friedl's excellent "Mastering Regular
Expressions" (O'Reilly). The title sounds like a library of
colloquialisms for people learning English as a secondary
language: "Howdy, there, how is it going?" "Is a cat keeping your
tongue?" Alas, that's not what regular expressions are about in a
JavaScript context.
Regular expressions are sequences of characters that define what to
match when searching a string of text. In the simplest case, this
regular expression /pants/ could tell a search function to register a
hit on the third word of the following string: "Ach, my pants are on
fire." Simple enough. The forward slashes are typically (though not
always) used to delimit regular expressions, by the way.
The real power of regular expressions comes when you use their support
for wildcards. This regular expression /[a-zA-Z]at/ matches the
characters "at" where they are preceded by an upper or lowercase
letter. Among the strings that would match the regular expression above
are: cat rat hat Hat aat Bat On the other hand, "9at" and "$at" would
not register hits. To associate a regular expression with a variable,
you just assign an expression like the one above (with forward-slashes,
without quotes) to a variable name, using the equality operator.
catsAndBats = /[a-zA-Z]at/ The variable becomes an object of type
RegExp, even if you don't cast it explicitly.
Although he doesn't deal with the specifics of regular expressions as
JavaScript implements them, I still recommend Friedl's book.