@@ -43,7 +43,11 @@ export default createRule("no-useless-string-literal", {
43
43
. join ( "|" )
44
44
if ( ! alternativesText . length ) {
45
45
const escape =
46
- isNeedEscapedInCharacterClass (
46
+ isNeedEscapeForAdjacentPreviousCharacter (
47
+ csdNode ,
48
+ saNode ,
49
+ ) ||
50
+ isNeedEscapeForAdjacentNextCharacter (
47
51
csdNode ,
48
52
saNode ,
49
53
)
@@ -60,12 +64,13 @@ export default createRule("no-useless-string-literal", {
60
64
saNode . raw === "^" ? "\\" : ""
61
65
return String . raw `[${ escape } ${ saNode . raw } \q{${ alternativesText } }]`
62
66
}
63
- const escape = isNeedEscapedInCharacterClass (
64
- csdNode ,
65
- saNode ,
66
- )
67
- ? "\\"
68
- : ""
67
+ const escape =
68
+ isNeedEscapeForAdjacentPreviousCharacter (
69
+ csdNode ,
70
+ saNode ,
71
+ )
72
+ ? "\\"
73
+ : ""
69
74
return String . raw `${ escape } ${ saNode . raw } \q{${ alternativesText } }`
70
75
} ) ,
71
76
} )
@@ -74,9 +79,10 @@ export default createRule("no-useless-string-literal", {
74
79
}
75
80
76
81
/**
77
- * Checks whether an escape is required if the given character when placed before a \q{...}
82
+ * Checks whether the given character requires escaping
83
+ * when adjacent to the previous character.
78
84
*/
79
- function isNeedEscapedInCharacterClass (
85
+ function isNeedEscapeForAdjacentPreviousCharacter (
80
86
disjunction : ClassStringDisjunction ,
81
87
character : StringAlternative ,
82
88
) {
@@ -97,6 +103,23 @@ export default createRule("no-useless-string-literal", {
97
103
disjunction . parent . start === disjunction . start - 1
98
104
)
99
105
}
106
+
107
+ /**
108
+ * Checks whether the given character requires escaping
109
+ * when adjacent to the next character.
110
+ */
111
+ function isNeedEscapeForAdjacentNextCharacter (
112
+ disjunction : ClassStringDisjunction ,
113
+ character : StringAlternative ,
114
+ ) {
115
+ const char = character . raw
116
+ // Avoid [\q{&}&&A] => [&&&A]
117
+ return (
118
+ RESERVED_DOUBLE_PUNCTUATOR_CHARS . has ( char ) &&
119
+ // The next character is the same
120
+ pattern [ disjunction . end ] === char
121
+ )
122
+ }
100
123
}
101
124
102
125
return defineRegexpVisitor ( context , {
0 commit comments