Java Reference
In-Depth Information
using the regexp objeCt's ConstruCtor
So far you've been creating RegExp objects using the / and / characters to define the start and end
of the regular expression, as shown in the following example:
var myRegExp = /[a-z]/;
Although this is the generally preferred method, it was briefly mentioned that a RegExp object can
also be created by means of the RegExp() constructor. You might use the first way most of the time.
However, on some occasions 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 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
expression 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 defined 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 define regular expressions with the / and / method, after the final / you could add
the special flags 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 flags 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");
 
Search WWH ::




Custom Search