no-useless-escape
禁止不必要的转义字符
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
此规则报告的一些问题可通过编辑器 建议 手动修复
转义字符串、模板字面和正则表达式中的非特殊字符没有任何效果,如下例所示:
¥Escaping non-special characters in strings, template literals, and regular expressions doesn’t have any effect, as demonstrated in the following example:
let foo = "hol\a"; // > foo = "hola"
let bar = `${foo}\!`; // > bar = "hola!"
let baz = /\:/ // same functionality with /:/
规则详情
¥Rule Details
此规则标记可以在不改变行为的情况下安全删除的转义。
¥This rule flags escapes that can be safely removed without changing behavior.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-useless-escape: "error"*/
"\'";
'\"';
"\#";
"\e";
`\"`;
`\"${foo}\"`;
`\#{foo}`;
/\!/;
/\@/;
/[\[]/;
/[a-z\-]/;
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-useless-escape: "error"*/
"\"";
'\'';
"\x12";
"\u00a9";
"\371";
"xs\u2111";
`\``;
`\${${foo}}`;
`$\{${foo}}`;
/\\/g;
/\t/g;
/\w\$\*\^\./;
/[[]/;
/[\]]/;
/[a-z-]/;
选项
¥Options
此规则有一个对象选项:
¥This rule has an object option:
-
allowRegexCharacters
- 正则表达式中允许包含不必要转义字符的字符数组。这对于像-
这样的字符非常有用,因为转义可以防止意外的字符范围。例如,在/[0\-]/
中,转义符在技术上是不必要的,但有助于防止模式在稍后添加其他字符时变成范围(例如,/[0\-9]/
与/[0-9]/
)。¥
allowRegexCharacters
- An array of characters that should be allowed to have unnecessary escapes in regular expressions. This is useful for characters like-
where escaping can prevent accidental character ranges. For example, in/[0\-]/
, the escape is technically unnecessary but helps prevent the pattern from becoming a range if another character is added later (e.g.,/[0\-9]/
vs/[0-9]/
).
allowRegexCharacters
{ "allowRegexCharacters": ["-"] }
选项的错误代码示例:
¥Examples of incorrect code for the { "allowRegexCharacters": ["-"] }
option:
/*eslint no-useless-escape: ["error", { "allowRegexCharacters": ["-"] }]*/
/\!/;
/\@/;
/[a-z\^]/;
{ "allowRegexCharacters": ["-"] }
选项的正确代码示例:
¥Examples of correct code for the { "allowRegexCharacters": ["-"] }
option:
/*eslint no-useless-escape: ["error", { "allowRegexCharacters": ["-"] }]*/
/[0\-]/;
/[\-9]/;
/a\-b/;
何时不使用
¥When Not To Use It
如果你不想收到有关不必要转义的通知,你可以安全地禁用此规则。
¥If you don’t want to be notified about unnecessary escapes, you can safely disable this rule.
版本
此规则是在 ESLint v2.5.0 中引入。