]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/require-unicode-regexp.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / require-unicode-regexp.md
1 # Enforce the use of `u` flag on RegExp (require-unicode-regexp)
2
3 RegExp `u` flag has two effects:
4
5 1. **Make the regular expression handling UTF-16 surrogate pairs correctly.**
6
7 Especially, character range syntax gets the correct behavior.
8
9 ```js
10 /^[👍]$/.test("👍") //→ false
11 /^[👍]$/u.test("👍") //→ true
12 ```
13
14 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).**
15
16 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.
17
18 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).
19
20 Therefore, the `u` flag lets us work better with regular expressions.
21
22 ## Rule Details
23
24 This rule aims to enforce the use of `u` flag on regular expressions.
25
26 Examples of **incorrect** code for this rule:
27
28 ```js
29 /*eslint require-unicode-regexp: error */
30
31 const a = /aaa/
32 const b = /bbb/gi
33 const c = new RegExp("ccc")
34 const d = new RegExp("ddd", "gi")
35 ```
36
37 Examples of **correct** code for this rule:
38
39 ```js
40 /*eslint require-unicode-regexp: error */
41
42 const a = /aaa/u
43 const b = /bbb/giu
44 const c = new RegExp("ccc", "u")
45 const d = new RegExp("ddd", "giu")
46
47 // This rule ignores RegExp calls if the flags could not be evaluated to a static value.
48 function f(flags) {
49 return new RegExp("eee", flags)
50 }
51 ```
52
53 ## When Not To Use It
54
55 If you don't want to notify regular expressions with no `u` flag, then it's safe to disable this rule.