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:

varpattern=/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:

varpattern=newRegExp("s$");

RegExp Literals and Object Creation

Literals of primitive type, like strings and numbers, evaluate
(obviously) to the same value each time they are encountered in a
program. Object literals (or initializers) such as {} and [] create a new object each time they are
encountered. If you write var a =
[] in the body of a loop, for example, each iteration of
the loop will create a new empty array.

Regular expression literals are a special case. The ECMAScript 3 specification says that a RegExp literal is converted to a RegExp object when the code is parsed, and each evaluation of the code returns the same object. The ECMAScript 5 specification reverses this and requires that each evaluation of a RegExp return a new object. IE has ...

The best content for your career. Discover unlimited learning
on demand for around $1/day.