Availability: |
| |||||||
JavaScript syntax: | - | new RegExp(aPattern) | ||||||
- | new RegExp(aPattern, someAttribs) | |||||||
Argument list: | aPattern | A regular expression-matching pattern contained in a string | ||||||
someAttribs | A string containing the regular expression attributes |
A RegExp constructor is used to create a new regular expression object containing a search pattern.
The first argument is a string containing a properly escaped pattern. Because the backslash character (\) is an escape when used in a string, for the back slashes to remain in the regular expression pattern, they will need to be double escaped. For example, this pattern:
/\d+/
Must be escaped like this when used in a string:
"\\d+"
The second argument is the attributes for the pattern. You should not put the attributes on the end of the pattern but specify them separately. These are available:
Operator | Description | JavaScript |
---|---|---|
i | Ignore case | JavaScript 1.2 |
g | Match globally | JavaScript 1.2 |
ig | Ignore case and match globally | JavaScript 1.2 |
m | Multiple line parsing | JavaScript 1.5 |
The regular expression constructor is useful for those occasions when you cannot easily predict what string you will need to match. If you could, it is likely you would use a regular expression literal. If the user is going to enter some value that determines what the search characteristics are to be then a RegExp() constructor may be useful.
// Declare a variable and assign a RegExp literal to it var myPattern = /x$/; // Now do the same thing with a RegExp constructor var myPattern = new RegExp("x$");
Prev | Home | Next |
RegExp object | Up | RegExp() |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |