JavaScript Editor JavaScript Validator     JavaScript Editor 

Team LiB
Previous Section Next Section

Using the RegExp Object's Constructor

So far we've been creating RegExp objects using the / and / characters to define the start and end of the regular expression, as shown in the following for example:

var myRegExp = /[a-z]/;

Although this is the generally preferred method, it was briefly mentioned that a RegExp object can also be created using the RegExp() constructor. While we might use the first way most of the time, there are occasions, as we'll see in the trivia quiz shortly, when the second way of creating a RegExp object is necessary (for example, when a regular expression is to be constructed from user input).

As an example, the preceding regular expression could equally well be defined as

var myRegExp = new RegExp("[a-z]");

Here we pass the regular expression as a string parameter to the RegExp() constructor function.

A very important difference when using this method is in how we use special regular expression char-acters, such as \b, which have a backward slash in front of them. The problem is that the backward slash indicates an escape character in JavaScript strings—for example, we may use \b, which means a backspace. To differentiate between \b meaning a backspace in a string and the \b special character in a regular expression, we have to put another backward slash in front of the regular expression special character. So \b becomes \\b when we mean the regular expression \b that matches a word boundary, rather than a backspace character.

For example, if we have defined our RegExp object using

var myRegExp = /\b/;

then declaring it using the RegExp() constructor, we would need to write this:

var myRegExp = new RegExp("\\b");

and not this:

var myRegExp = new RegExp("\b");

All special regular expression characters, such as \w, \b, \d, and so on, must have an extra \ in front when created using RegExp().

When we defined regular expressions with the / and / method, we could add after the final / the special flags m, g, and i to indicate that the pattern matching should be multi-line, global, or case-insensitive. When using the RegExp() constructor, how can we do the same thing?

Easy. The optional second parameter of the RegExp() constructor takes the flags that specify a global or case-insensitive match. For example

var myRegExp = new RegExp("hello\\b","gi");

will do a global case-insensitive pattern match. We can specify just one of the flags if we wish, such as the following:

var myRegExp = new RegExp("hello\\b","i");


var myRegExp = new RegExp("hello\\b","g");

Team LiB
Previous Section Next Section

JavaScript Editor JavaScript Validator     JavaScript Editor