1. Computing
Send to a Friend via Email

Regular Expressions

19. The RegExp Object

clr gif

Throughout this tutorial series I have shown you how to code your regular expressions by enclosing them between slashes. There is actually a second way to define a regular expression using a more normal Javascript statement style of coding.

There are three reasons why I have used the less Javascript-like way of coding regular expressions throughout these tutorials.

  • It is the more common method that people use to code regular expressions.
  • It is the shorter of the two methods.
  • It avoids an additional complexity in the way that you define the pattern.

The more Javascript-like way of defining a regular expression is to define a variable as a new RegExp object. That object takes one or two parameters corresponding to the regular expression pattern and any qualifiers that follow the pattern. The following two regular expression declarations are equivalent:

var re = /\bthe\b/ig;
var re2 = new RegExp('\\bthe\\b','ig');

As you can see, the second version does have a more normal Javascript appearance but is significantly longer.

Surrounding the regular expression between slashes is a useful shortcut that is identically equivalent to creating a RegExp object (in the same way that surrounding the entries in [] is a shortcut for creating an Array and {} is a shortcut for creating an Object). The /exp/ method also avoids the problem of having to double escape and regular expression escape codes. The reason why we need to specify \\ in place of \ throughout our expression when we use the RegExp declaration is that when we use this method the \ has its regular Javascript meaning as a Javascript escape character and so we need to escape that Javascript special meaning (by preceding it by a \) in order to pass it as a \ to the regular expression. Using the alternative and more common method of defining a regular expression avoids that additional complexity.

A RegExp object once defined can be used in exactly the same way whichever of the two methods are used to define it.

©2014 About.com. All rights reserved.