Skip to content

Commit a23a69c

Browse files
committed
fix: Escape RegExp characters in suffix.
1 parent 797b2bb commit a23a69c

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

source/rules/suffix-subjects.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
getParserServices,
1212
getTypeServices,
1313
} from "eslint-etc";
14-
import { ruleCreator } from "../utils";
14+
import { escapeRegExp, ruleCreator } from "../utils";
1515

1616
const defaultOptions: readonly {
1717
parameters?: boolean;
@@ -75,7 +75,10 @@ const rule = ruleCreator({
7575
}
7676

7777
const { suffix = "Subject" } = config;
78-
const suffixRegex = new RegExp(String.raw`${suffix}\$?$`, "i");
78+
const suffixRegex = new RegExp(
79+
String.raw`${escapeRegExp(suffix)}\$?$`,
80+
"i"
81+
);
7982

8083
function checkNode(nameNode: es.Node, typeNode?: es.Node) {
8184
let tsNode = esTreeNodeToTSNodeMap.get(nameNode);

source/utils.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ export function createRegExpForWords(
2020
return new RegExp(`(${joined})`, flags);
2121
}
2222

23+
export function escapeRegExp(text: string): string {
24+
// https://stackoverflow.com/a/3561711/6680611
25+
return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
26+
}
27+
2328
export const ruleCreator = ESLintUtils.RuleCreator(
2429
(name) =>
2530
`https://github.com/cartant/eslint-plugin-rxjs/tree/main/docs/rules/${name}.md`

tests/rules/suffix-subjects.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,19 @@ ruleTester({ types: true }).run("suffix-subjects", rule, {
591591
~~~~~~ [forbidden { "suffix": "Subject" }]
592592
`
593593
),
594+
fromFixture(
595+
stripIndent`
596+
// BehaviorSubject with $$ suffix
597+
// https://github.com/cartant/eslint-plugin-rxjs/issues/88
598+
import { BehaviorSubject } from "rxjs";
599+
600+
const subject$ = new BehaviorSubject<number>(42);
601+
~~~~~~~~ [forbidden { "suffix": "$$" }]
602+
const someSubject$ = new BehaviorSubject<number>(54);
603+
~~~~~~~~~~~~ [forbidden { "suffix": "$$" }]
604+
`,
605+
{ options: [{ suffix: "$$" }] }
606+
),
594607
fromFixture(
595608
stripIndent`
596609
// MySubject without suffix

0 commit comments

Comments
 (0)