Skip to content

Commit

Permalink
better-regexp: Don't fix if .source or .toString() is used (#1903)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Sep 19, 2022
1 parent 02252c7 commit 8ad592b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
21 changes: 19 additions & 2 deletions rules/better-regex.js
Expand Up @@ -51,15 +51,32 @@ const create = context => {
return;
}

return {
const problem = {
node,
messageId: MESSAGE_ID,
data: {
original,
optimized,
},
fix: fixer => fixer.replaceText(node, optimized),
};

if (
node.parent.type === 'MemberExpression'
&& node.parent.object === node
&& !node.parent.optional
&& !node.parent.computed
&& node.parent.property.type === 'Identifier'
&& (
node.parent.property.name === 'toString'
|| node.parent.property.name === 'source'
)
) {
return problem;
}

return Object.assign(problem, {
fix: fixer => fixer.replaceText(node, optimized),
});
},
[newRegExp](node) {
const [patternNode, flagsNode] = node.arguments;
Expand Down
10 changes: 10 additions & 0 deletions test/better-regex.mjs
Expand Up @@ -311,5 +311,15 @@ test({
],
parser: require.resolve('@typescript-eslint/parser'),
},

// Not fixable
{
code: 'const foo = /[0-9]/.toString',
errors: createError('/[0-9]/', '/\\d/'),
},
{
code: 'const foo = /[0-9]/.source',
errors: createError('/[0-9]/', '/\\d/'),
},
],
});

0 comments on commit 8ad592b

Please sign in to comment.