Skip to content

Commit c201987

Browse files
authored
better-regex: Fix empty-pattern autofix (#2881)
1 parent c7f57d0 commit c201987

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

rules/better-regex.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ const messages = {
1010
[MESSAGE_ID_PARSE_ERROR]: 'Problem parsing {{original}}: {{error}}',
1111
};
1212

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+
1321
/** @param {import('eslint').Rule.RuleContext} context */
1422
const create = context => {
1523
const {sortCharacterClasses} = context.options[0];
@@ -36,6 +44,7 @@ const create = context => {
3644

3745
try {
3846
optimized = regexpTree.optimize(original, undefined, {blacklist: ignoreList}).toString();
47+
optimized = normalizeOptimizedRegexLiteral(optimized);
3948
} catch (error) {
4049
return {
4150
node,

test/better-regex.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,26 @@ test({
8989
errors: createError(String.raw`/\w/ig`, String.raw`/\w/gi`),
9090
output: String.raw`const foo = /\w/gi`,
9191
},
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+
output: String.raw`const expression = /(?:)/`,
106+
},
107+
{
108+
code: String.raw`const expression = /(?:)|/g`,
109+
errors: createError(String.raw`/(?:)|/g`, String.raw`/(?:)/g`),
110+
output: String.raw`const expression = /(?:)/g`,
111+
},
92112
{
93113
code: 'const foo = /[0-9]/',
94114
errors: createError('/[0-9]/', String.raw`/\d/`),

0 commit comments

Comments
 (0)