]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/require-unicode-regexp.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / require-unicode-regexp.md
1 ---
2 title: require-unicode-regexp
3 rule_type: suggestion
4 ---
5
6
7 RegExp `u` flag has two effects:
8
9 1. **Make the regular expression handling UTF-16 surrogate pairs correctly.**
10
11 Especially, character range syntax gets the correct behavior.
12
13 ```js
14 /^[👍]$/.test("👍") //→ false
15 /^[👍]$/u.test("👍") //→ true
16 ```
17
18 2. **Make the regular expression throwing syntax errors early as disabling [Annex B extensions](https://www.ecma-international.org/ecma-262/6.0/#sec-regular-expressions-patterns).**
19
20 Because of historical reason, JavaScript regular expressions are tolerant of syntax errors. For example, `/\w{1, 2/` is a syntax error, but JavaScript doesn't throw the error. It matches strings such as `"a{1, 2"` instead. Such a recovering logic is defined in Annex B.
21
22 The `u` flag disables the recovering logic Annex B defined. As a result, you can find errors early. This is similar to [the strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode).
23
24 Therefore, the `u` flag lets us work better with regular expressions.
25
26 ## Rule Details
27
28 This rule aims to enforce the use of `u` flag on regular expressions.
29
30 Examples of **incorrect** code for this rule:
31
32 ::: incorrect
33
34 ```js
35 /*eslint require-unicode-regexp: error */
36
37 const a = /aaa/
38 const b = /bbb/gi
39 const c = new RegExp("ccc")
40 const d = new RegExp("ddd", "gi")
41 ```
42
43 :::
44
45 Examples of **correct** code for this rule:
46
47 ::: correct
48
49 ```js
50 /*eslint require-unicode-regexp: error */
51
52 const a = /aaa/u
53 const b = /bbb/giu
54 const c = new RegExp("ccc", "u")
55 const d = new RegExp("ddd", "giu")
56
57 // This rule ignores RegExp calls if the flags could not be evaluated to a static value.
58 function f(flags) {
59 return new RegExp("eee", flags)
60 }
61 ```
62
63 :::
64
65 ## When Not To Use It
66
67 If you don't want to notify regular expressions with no `u` flag, then it's safe to disable this rule.