]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # disallow invalid regular expression strings in `RegExp` constructors (no-invalid-regexp) |
2 | ||
3 | An invalid pattern in a regular expression literal is a `SyntaxError` when the code is parsed, but an invalid string in `RegExp` constructors throws a `SyntaxError` only when the code is executed. | |
4 | ||
5 | ## Rule Details | |
6 | ||
7 | This rule disallows invalid regular expression strings in `RegExp` constructors. | |
8 | ||
9 | Examples of **incorrect** code for this rule: | |
10 | ||
11 | ```js | |
12 | /*eslint no-invalid-regexp: "error"*/ | |
13 | ||
14 | RegExp('[') | |
15 | ||
16 | RegExp('.', 'z') | |
17 | ||
18 | new RegExp('\\') | |
19 | ``` | |
20 | ||
21 | Examples of **correct** code for this rule: | |
22 | ||
23 | ```js | |
24 | /*eslint no-invalid-regexp: "error"*/ | |
25 | ||
26 | RegExp('.') | |
27 | ||
28 | new RegExp | |
29 | ||
30 | this.RegExp('[') | |
31 | ``` | |
32 | ||
456be15e | 33 | Please note that this rule validates regular expressions per the latest ECMAScript specification, regardless of your parser settings. |
eb39fafa | 34 | |
456be15e | 35 | If you want to allow additional constructor flags for any reason, you can specify them using the `allowConstructorFlags` option. These flags will then be ignored by the rule. |
eb39fafa DC |
36 | |
37 | ## Options | |
38 | ||
39 | This rule has an object option for exceptions: | |
40 | ||
41 | * `"allowConstructorFlags"` is an array of flags | |
42 | ||
43 | ### allowConstructorFlags | |
44 | ||
456be15e | 45 | Examples of **correct** code for this rule with the `{ "allowConstructorFlags": ["a", "z"] }` option: |
eb39fafa DC |
46 | |
47 | ```js | |
456be15e | 48 | /*eslint no-invalid-regexp: ["error", { "allowConstructorFlags": ["a", "z"] }]*/ |
eb39fafa | 49 | |
456be15e | 50 | new RegExp('.', 'a') |
eb39fafa | 51 | |
456be15e | 52 | new RegExp('.', 'az') |
eb39fafa DC |
53 | ``` |
54 | ||
55 | ## Further Reading | |
56 | ||
57 | * [Annotated ES5 ยง7.8.5 - Regular Expression Literals](https://es5.github.io/#x7.8.5) |