How to create regular expression with RegExp constructor
Description
Regular expressions can be created by using the RegExp
constructor,
which accepts two arguments:
- a string pattern to match and
- an optional string of flags to apply.
Example
// Match the first instance of "bat" or "cat", regardless of case.
var pattern1 = /at/i;
/*from w ww. j av a2 s . co m*/
// Same as pattern1, using the constructor.
var pattern2 = new RegExp("at", "i");
Note
Double-escape are needed for RegExp constructor since it accepts string as parameter.
The following table compares patterns in literal form and cooresponding form in the RegExp constructor.
LITERAL PATTERN | STRING EQUIVALENT |
---|---|
/\[ab\]at/ | "\\[ab\\]at" |
/\.ab/ | "\\.ab" |
/name\/age/ | "name\\/age" |
/\d.\d{1,2}/ | "\\d.\\d{1,2}" |
/\w\\hello\\456/ | "\\w\\\\hello\\\\456" |