javascript - Getting an ESLint: Unnecessary escape character - Stack Overflow

I'm trying to validate a text field but, I'm getting an error for the below regex expression.

I'm trying to validate a text field but, I'm getting an error for the below regex expression.

if (!/^[a-zA-Z0-9\\\/\*+;&%?#@!^()_="\-:~`|[\]\{\}\s]*$/i.test(e.target.value)) {
   this.setState({
      newFamilyName: e.target.value,
   });
}

Do I need to add any more characters in the Regex so fulfill it.

I'm trying to validate a text field but, I'm getting an error for the below regex expression.

if (!/^[a-zA-Z0-9\\\/\*+;&%?#@!^()_="\-:~`|[\]\{\}\s]*$/i.test(e.target.value)) {
   this.setState({
      newFamilyName: e.target.value,
   });
}

Do I need to add any more characters in the Regex so fulfill it.

Share Improve this question edited Nov 5, 2019 at 4:08 Mohamed Ibrahim Elsayed 2,9843 gold badges26 silver badges46 bronze badges asked Nov 4, 2019 at 22:02 tejasree vangapallitejasree vangapalli 891 silver badge11 bronze badges 2
  • I mean... if the escape character is "unnecessary", wouldn't that indicate removing characters rather than adding? – Kevin B Commented Nov 4, 2019 at 22:13
  • I've edited my answer with a fix. You can mark it as solved if it helped. – Nicolas Hevia Commented Nov 6, 2019 at 5:11
Add a ment  | 

2 Answers 2

Reset to default 4

You have some unnecesary escape characters: \/ \* \{ \}

You can fix it:

if (!/^[a-zA-Z0-9\\/*+;&%?#@!^()_="\-:~`|[\]{}\s]*$/i.test(e.target.value)) {
   this.setState({
      newFamilyName: e.target.value,
   });
}

Or disable the rule:

//eslint-disable-next-line
if (!/^[a-zA-Z0-9\\\/\*+;&%?#@!^()_="\-:~`|[\]\{\}\s]*$/i.test(e.target.value)) {
   this.setState({
      newFamilyName: e.target.value,
   });
}

Unnecessary escape character means you have a \ in front of a character in your regex that you don't actually need.

I plugged the code you posted into https://eslint/demo and got:

1:20 - Unnecessary escape character: \/. (no-useless-escape)
1:22 - Unnecessary escape character: \*. (no-useless-escape)
1:47 - Unnecessary escape character: \{. (no-useless-escape)
1:49 - Unnecessary escape character: \}. (no-useless-escape)

Which means you didn't need the \ in front of the /, *, {, or } in your regex. Those characters don't need to be escaped since they appeared inside the [] group.

Unfortunately the "Fixed Code" thing on the eslint demo site didn't work, but the following code is how you would fix it

if (!/^[a-zA-Z0-9\\/*+;&%?#@!^()_="\-:~`|[\]{}\s]*$/i.test(e.target.value)) {
   this.setState({
      newFamilyName: e.target.value,
   });
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744169229a4561452.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信