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.
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
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");