JavaScript RegExp()
The RegExp() constructor creates regular expression objects.
Regular expressions are patterns used to match character combinations in strings.
Regular expressions are usually created with regular expression literals.
Parameters
| Parameter | Description |
|---|---|
| pattern | A regular expression pattern or an existing RegExp object. |
| flags | Optional. Modifiers such as g, i, m, s, u, v, or y. |
Literal vs Constructor
Regular expressions are normally created with a regular expression literal.
The constructor is useful when the pattern must be built dynamically.
Literal
const pattern = /w3schools/i;
Constructor
const pattern = new RegExp("w3schools", "i");
Dynamic Patterns
The constructor allows patterns to be built from variables.
Example
const text = "W3Schools";
const pattern = new RegExp(text, "i");
Return Value
| Call | Returns |
|---|---|
RegExp(...) |
A RegExp object |
new RegExp(...) |
A RegExp object |
Object Hierarchy
RegExp objects inherit from Object.
Object └─ RegExp
| Constructor Type | Function |
| Creates | RegExp objects |
| Inherits From | Object |
Common Flags
| Flag | Description |
|---|---|
| g | Global search |
| i | Case-insensitive search |
| m | Multiline search |
| s | Dot matches line breaks |
| u | Unicode mode |
| v | Unicode sets mode |
| y | Sticky search |
RegExp objects provide properties and methods for working with regular expressions.
exec()test()sourceflagslastIndex
Use regular expression literals when the pattern is known in advance.
Use the RegExp() constructor when the pattern must be created dynamically.
Related Pages:
Object Type
The RegExp() constructor creates RegExp objects.
RegExp objects inherit from Object.
Unlike String, Number, and Boolean, there is no primitive RegExp type.
A RegExp is always an object.
Browser Support
new RegExp() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |