Java Reference
In-Depth Information
Although this is the generally preferred method, it was briefl y mentioned that a RegExp object can also
be created by means of the RegExp() constructor. You might use the fi rst way most of the time. However,
there are occasions, as you'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 defi ned as
var myRegExp = new RegExp(“[a-z]”);
Here you pass the regular expression as a string parameter to the RegExp() constructor function.
A very important difference when you are using this method is in how you use special regular expres-
sion characters, such as \b, that have a backward slash in front of them. The problem is that the backward
slash indicates an escape character in JavaScript strings — for example, you 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, you have to put another backward slash in front of the regular expression special
character. So \b becomes \\b when you mean the regular expression \b that matches a word boundary,
rather than a backspace character.
For example, say you have defi ned your RegExp object using the following:
var myRegExp = /\b/;
To declare it using the RegExp() constructor, you 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 you create them using RegExp().
When you defi ned regular expressions with the / and / method, you could add after the fi nal / the spe-
cial fl ags m, g, and i to indicate that the pattern matching should be multi-line, global, or case-insensitive,
respectively. When using the RegExp() constructor, how can you do the same thing?
Easy. The optional second parameter of the RegExp() constructor takes the fl ags that specify a global
or case-insensitive match. For example, this will do a global case-insensitive pattern match:
var myRegExp = new RegExp(“hello\\b”,”gi”);
You can specify just one of the fl ags if you wish — such as the following:
var myRegExp = new RegExp(“hello\\b”,”i”);
or
var myRegExp = new RegExp(“hello\\b”,”g”);
Search WWH ::




Custom Search