Defining Regular Expressions
In JavaScript, regular expressions are represented by RegExp
objects. RegExp objects may be created with the RegExp()
constructor, of course, but they
are more often created using a special literal syntax. Just as string
literals are specified as characters within quotation marks, regular
expression literals are specified as characters within a pair of slash
(/
) characters. Thus, your
JavaScript code may contain lines like this:
var
pattern
=
/s$/
;
This line creates a new RegExp object and assigns it to the
variable pattern
. This particular
RegExp object matches any string that ends with the letter “s.” This
regular expression could have equivalently been defined with the
RegExp()
constructor like
this:
var
pattern
=
new
RegExp
(
"s$"
);
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.