Skip to content

Commit 381d412

Browse files
authored
Fix false positives for match with g flag in regexp/prefer-regexp-test rule (#73)
1 parent 91a6ac8 commit 381d412

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

lib/rules/prefer-regexp-test.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import type * as ES from "estree"
2-
import { hasSideEffect, isOpeningParenToken } from "eslint-utils"
2+
import {
3+
getStaticValue,
4+
hasSideEffect,
5+
isOpeningParenToken,
6+
} from "eslint-utils"
37
import { createRule } from "../utils"
48
import { createTypeTracker } from "../utils/type-tracker"
59
import { isKnownMethodCall } from "../utils/ast-utils"
@@ -37,6 +41,16 @@ export default createRule("prefer-regexp-test", {
3741
if (!typeTracer.isString(node.callee.object)) {
3842
return
3943
}
44+
const arg = node.arguments[0]
45+
const evaluated = getStaticValue(arg, context.getScope())
46+
if (
47+
evaluated &&
48+
evaluated.value instanceof RegExp &&
49+
evaluated.value.flags.includes("g")
50+
) {
51+
return
52+
}
53+
4054
const memberExpr = node.callee
4155
context.report({
4256
node,

tests/lib/rules/prefer-regexp-test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,5 +115,33 @@ tester.run("prefer-regexp-test", rule as any, {
115115
"Use the `RegExp#test()` method instead of `String#match`, if you need a boolean.",
116116
],
117117
},
118+
{
119+
code: `
120+
const re = /a/g;
121+
const str = 'abc';
122+
123+
console.log(!!str.match(re)); // ignore
124+
console.log(!!str.match(re)); // ignore
125+
console.log(!!re.exec(str));
126+
console.log(!!re.exec(str));
127+
console.log(re.test(str));
128+
console.log(re.test(str));
129+
`,
130+
output: `
131+
const re = /a/g;
132+
const str = 'abc';
133+
134+
console.log(!!str.match(re)); // ignore
135+
console.log(!!str.match(re)); // ignore
136+
console.log(!!re.test(str));
137+
console.log(!!re.test(str));
138+
console.log(re.test(str));
139+
console.log(re.test(str));
140+
`,
141+
errors: [
142+
"Use the `RegExp#test()` method instead of `RegExp#exec`, if you need a boolean.",
143+
"Use the `RegExp#test()` method instead of `RegExp#exec`, if you need a boolean.",
144+
],
145+
},
118146
],
119147
})

0 commit comments

Comments
 (0)