diff --git a/.changeset/spicy-rats-invent.md b/.changeset/spicy-rats-invent.md new file mode 100644 index 000000000..a4ddbfc3d --- /dev/null +++ b/.changeset/spicy-rats-invent.md @@ -0,0 +1,5 @@ +--- +"eslint-plugin-regexp": patch +--- + +fix(sort-character-class-elements): wrong autofix for `^` diff --git a/lib/rules/sort-character-class-elements.ts b/lib/rules/sort-character-class-elements.ts index 8ea0d6448..f2ed2cc33 100644 --- a/lib/rules/sort-character-class-elements.ts +++ b/lib/rules/sort-character-class-elements.ts @@ -296,6 +296,15 @@ function escapeRaw(node: CharacterClassElement, target: CharacterClassElement) { ) { raw = `\\${raw}` } + } else if (raw.startsWith("^")) { + const parent = target.parent as CharacterClass + const elements: ( + | UnicodeSetsCharacterClassElement + | ClassRangesCharacterClassElement + )[] = parent.elements + if (elements.indexOf(target) === 0) { + raw = `\\${raw}` + } } if (target.raw.startsWith("-")) { if (node.type === "Character" || node.type === "CharacterSet") { diff --git a/tests/lib/rules/__snapshots__/sort-character-class-elements.ts.eslintsnap b/tests/lib/rules/__snapshots__/sort-character-class-elements.ts.eslintsnap index 81d78e81a..957f5853f 100644 --- a/tests/lib/rules/__snapshots__/sort-character-class-elements.ts.eslintsnap +++ b/tests/lib/rules/__snapshots__/sort-character-class-elements.ts.eslintsnap @@ -375,3 +375,29 @@ Output: [1] Expected character class elements to be in ascending order. '\q{aa}' should be before '\q{ab}'. --- + + +Test: sort-character-class-elements >> invalid +Code: + 1 | /[~^*]/ + | ^ [1] + | ^ [2] + +Output: + 1 | /[*\^~]/ + +[1] Expected character class elements to be in ascending order. '^' should be before '~'. +[2] Expected character class elements to be in ascending order. '*' should be before '~'. +--- + + +Test: sort-character-class-elements >> invalid +Code: + 1 | /[~^]/ + | ^ [1] + +Output: + 1 | /[\^~]/ + +[1] Expected character class elements to be in ascending order. '^' should be before '~'. +--- diff --git a/tests/lib/rules/sort-character-class-elements.ts b/tests/lib/rules/sort-character-class-elements.ts index 6c40689c9..38b50e2ca 100644 --- a/tests/lib/rules/sort-character-class-elements.ts +++ b/tests/lib/rules/sort-character-class-elements.ts @@ -96,5 +96,7 @@ tester.run("sort-character-class-elements", rule as any, { String.raw`/[\q{b}\q{c}\q{a}]/v`, String.raw`/[\q{ac}\q{ab}\q{aa}]/v`, String.raw`/[\q{ab}\q{ac}\q{aa}]/v`, + String.raw`/[~^*]/`, + String.raw`/[~^]/`, ], })