]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/prefer-named-capture-group.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / prefer-named-capture-group.md
1 ---
2 title: prefer-named-capture-group
3 layout: doc
4 rule_type: suggestion
5 related_rules:
6 - no-invalid-regexp
7 ---
8
9
10 ## Rule Details
11
12 With the landing of ECMAScript 2018, named capture groups can be used in regular expressions, which can improve their readability.
13 This rule is aimed at using named capture groups instead of numbered capture groups in regular expressions:
14
15 ```js
16 const regex = /(?<year>[0-9]{4})/;
17 ```
18
19 Alternatively, if your intention is not to _capture_ the results, but only express the alternative, use a non-capturing group:
20
21 ```js
22 const regex = /(?:cauli|sun)flower/;
23 ```
24
25 Examples of **incorrect** code for this rule:
26
27 ::: incorrect
28
29 ```js
30 /*eslint prefer-named-capture-group: "error"*/
31
32 const foo = /(ba[rz])/;
33 const bar = new RegExp('(ba[rz])');
34 const baz = RegExp('(ba[rz])');
35
36 foo.exec('bar')[1]; // Retrieve the group result.
37 ```
38
39 :::
40
41 Examples of **correct** code for this rule:
42
43 ::: correct
44
45 ```js
46 /*eslint prefer-named-capture-group: "error"*/
47
48 const foo = /(?<id>ba[rz])/;
49 const bar = new RegExp('(?<id>ba[rz])');
50 const baz = RegExp('(?<id>ba[rz])');
51 const xyz = /xyz(?:zy|abc)/;
52
53 foo.exec('bar').groups.id; // Retrieve the group result.
54 ```
55
56 :::
57
58 ## When Not To Use It
59
60 If you are targeting ECMAScript 2017 and/or older environments, you should not use this rule, because this ECMAScript feature is only supported in ECMAScript 2018 and/or newer environments.