Skip to content

Commit bc0a29e

Browse files
authored
Fix false positives for replacer function with rest arg in regexp/no-unused-capturing-group rule (#354)
1 parent a227562 commit bc0a29e

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/utils/extract-capturing-group-references.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,10 @@ function* iterateForReplacerFunction(
524524
on: "replace" | "replaceAll",
525525
ctx: ExtractCapturingGroupReferencesContext,
526526
): Iterable<CapturingGroupReference> {
527-
if (replacementNode.params.length < 2) {
527+
if (
528+
replacementNode.params.length < 2 &&
529+
!replacementNode.params.some((arg) => arg.type === "RestElement")
530+
) {
528531
yield {
529532
type: "WithoutRef",
530533
node: argument,

tests/lib/rules/no-unused-capturing-group.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,21 @@ tester.run("no-unused-capturing-group", rule as any, {
119119
"var replaced = '2000-12-31'.replace(/(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})/, (_, y, m, d, o, s, g) => `${g.y}/${g.m}/${g.d}`)",
120120
String.raw`'2000-12-31'.replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/u, '$1/$2/$3') // "2000/12/31"`,
121121
String.raw`const [,y,m,d] = '2000-12-31'.match(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/)`,
122+
// https://github.com/ota-meshi/eslint-plugin-regexp/issues/353
123+
`const string = 'foo:abc,bar:def'.replace(/foo:(?<foo>\\w+),bar:(?<bar>\\w+)/, (...args) => {
124+
const { foo, bar } = args.at(-1);
125+
return \`\${ bar },\${ foo }\`;
126+
});`,
127+
String.raw`
128+
const regexp = /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/
129+
let match
130+
while(match = regexp.exec(foo)) {
131+
const m = [...match]
132+
}
133+
`,
134+
String.raw`
135+
const matches = [...('2000-12-31 2000-12-31'.matchAll(/(\d{4})-(\d{2})-(\d{2})/g))]
136+
`,
122137
],
123138
invalid: [
124139
{
@@ -450,5 +465,9 @@ tester.run("no-unused-capturing-group", rule as any, {
450465
},
451466
],
452467
},
468+
{
469+
code: `'str'.replace(/(?<foo>\\w+)/, () => {});`,
470+
errors: ["Capturing group 'foo' is defined but never used."],
471+
},
453472
],
454473
})

0 commit comments

Comments
 (0)