禁用不必要的转义字符:\/ no-useless-escape

Disable Unnecessary escape character: \/ no-useless-escape

我有这个正则表达式,它会检查字符串是否包含 link 或 url (i.e. https://eslint.org/docs/rules/no-useless-escape)。使用此正则表达式 /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,我在 运行 我的测试用例对 Unnecessary escape character: \/ no-useless-escape 做出反应时遇到了错误。如何禁用此 eslint-error 以便我继续我的测试用例并使用正则表达式。

感谢您的帮助!

它是 [-A-Z0-9+&@#\/%?=~_|!:,.;][-A-Z0-9+&@#\/%=~_|] 中的 \/(不是 :\/\/ 中的)。大多数字符不必在字符 class(方括号)内转义。这应该是等价的:/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig 有关详细信息,请参阅 https://www.regular-expressions.info/charclass.html,但相关部分:

In most regex flavors, the only special characters or metacharacters inside a character class are the closing bracket ], the backslash , the caret ^, and the hyphen -. The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.

您可以使用 ESLint 并尝试添加以下任一内容:-

  1. //eslint-disable-line 上线以禁用警告。
  2. //eslint-disable-next-line 到禁用警告之前的行。

参见 ESLint 文档,Disabling Rules with Inline Comments

To disable all rules on a specific line, use a line or block comment in one of the following formats:

alert('foo'); // eslint-disable-line

// eslint-disable-next-line
alert('foo');

/* eslint-disable-next-line */
alert('foo');

alert('foo'); /* eslint-disable-line */

您可以通过在文件顶部添加 /* eslint-disable */ 来禁用整个文件中的警告。

To disable rule warnings in an entire file, put a /* eslint-disable */ block comment at the top of the file:

/* eslint-disable */
   alert('foo');

\ 在我的 NodeJS typescript 项目中给出以下代码的错误,代码编辑器是 VS Code -

代码-

if (!(/^[\-0-9a-zA-Z\.\+_]+@[\-0-9a-zA-Z\.\+_]+\.[a-zA-Z]{2,}$/).test(String(req.body.email))) { ... }

错误-

Unnecessary escape character: \+. (eslintno-useless-escape)

解决方案-

//eslint-disable-next-line

最终代码-

//eslint-disable-next-line
if (!(/^[\-0-9a-zA-Z\.\+_]+@[\-0-9a-zA-Z\.\+_]+\.[a-zA-Z]{2,}$/).test(String(req.body.email))) { ... }
//eslint-disable-next-line

将其放在代码行上方

/*eslint no-undef: 0*/

将其放在文件的第一行(或脚本标签的第一行) 这将使整个文件禁用 eslint

您也可以使用

/* eslint-disable no-useless-escape */

禁用整个脚本文件的规则。

我在反应中有类似的警告。

Unnecessary escape character: \# no-useless-escape

只需删除警告中提到的任何内容即可。就我而言,警告中有 \#,所以我只是将其从警告中提到的行中删除。

我有以下用于验证电子邮件地址的代码片段:

/[a-zA-Z0-9\.]*@[a-z]*[\.a-z]*/.test(value)

由于“\.”,linter 显示错误。在方括号 ('[]') 内。方括号不需要转义字符 ('\') 即可使用 '.'。我删除了“[]”中的“\”(如下所示),错误得到解决。

/[a-zA-Z0-9.]*@[a-z]*[.a-z]*/.test(value)