Team LiB
Previous Section Next Section

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.

var country = new RegExp("England");
var geographicLocation = "New England";

document.write("Destination for work: "+geographicLocation+"<<br />>");
geographicLocation = geographicLocation.replace(country, "Zealand");
document.write("Destination for vacation: "+geographicLocation);

The result of the execution of this script is shown next.

Click To expand

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.


Team LiB
Previous Section Next Section