We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
better-regex
1 parent c7f57d0 commit c201987Copy full SHA for c201987
2 files changed
rules/better-regex.js
@@ -10,6 +10,14 @@ const messages = {
10
[MESSAGE_ID_PARSE_ERROR]: 'Problem parsing {{original}}: {{error}}',
11
};
12
13
+// `regexp-tree` can optimize `/|/` into `//`, which is not valid JavaScript syntax.
14
+// Normalize to an explicit empty alternative so the autofix always stays parseable.
15
+const normalizeOptimizedRegexLiteral = optimizedRegexLiteral => (
16
+ optimizedRegexLiteral.startsWith('//')
17
+ ? `/(?:)/${optimizedRegexLiteral.slice(2)}`
18
+ : optimizedRegexLiteral
19
+);
20
+
21
/** @param {import('eslint').Rule.RuleContext} context */
22
const create = context => {
23
const {sortCharacterClasses} = context.options[0];
@@ -36,6 +44,7 @@ const create = context => {
36
44
37
45
try {
38
46
optimized = regexpTree.optimize(original, undefined, {blacklist: ignoreList}).toString();
47
+ optimized = normalizeOptimizedRegexLiteral(optimized);
39
48
} catch (error) {
40
49
return {
41
50
node,
test/better-regex.js
@@ -89,6 +89,26 @@ test({
89
errors: createError(String.raw`/\w/ig`, String.raw`/\w/gi`),
90
output: String.raw`const foo = /\w/gi`,
91
},
92
+ {
93
+ code: String.raw`const expression = /|/`,
94
+ errors: createError(String.raw`/|/`, String.raw`/(?:)/`),
95
+ output: String.raw`const expression = /(?:)/`,
96
+ },
97
98
+ code: String.raw`const expression = /|/g`,
99
+ errors: createError(String.raw`/|/g`, String.raw`/(?:)/g`),
100
+ output: String.raw`const expression = /(?:)/g`,
101
102
103
+ code: String.raw`const expression = /(?:)|/`,
104
+ errors: createError(String.raw`/(?:)|/`, String.raw`/(?:)/`),
105
106
107
108
+ code: String.raw`const expression = /(?:)|/g`,
109
+ errors: createError(String.raw`/(?:)|/g`, String.raw`/(?:)/g`),
110
111
112
{
113
code: 'const foo = /[0-9]/',
114
errors: createError('/[0-9]/', String.raw`/\d/`),
0 commit comments