Regular Expressions

The last major functional feature of JavaScript is the regular expression. A regular expression as defined by the RegExp constructor is used to carry out pattern matching.

var country = new RegExp("England");

This could have been defined as well using a direct assignment:

var country = /England/;

Once a regular expression is defined, we can use it to pattern-match and potentially change strings. The following simple example matches a piece of the string in the variable .geographicLocation and substitutes it for another string.

JavaScript’s implementation of regular expressions is extremely powerful and very similar to Perl’s, so many programmers should be immediately comfortable with JavaScript regular expression facilities. More information on regular expressions can be found in Chapter 8.