简体   繁体   English

JavaScript正则表达式不能替换'@'字符

[英]JavaScript regex not replacing '@' character

I am new to JavaScipt and testing a regular Expression and is working on below use case - 我是JavaScipt的新手,正在测试一个正则表达式,并且正在研究以下用例-

Requirement - Replace every character with '#' that is NOT FROM BELOW LIST - 要求-用非以下列表中的 '#'替换每个字符-

  • Number
  • Character (upper or lower case) 字符(大写或小写)
  • Any special character except -> comma, dot, square brackets, forward slash, single Quote 除->逗号,点,方括号,正斜杠,单引号外的任何特殊字符

Please find my code below - 请在下面找到我的代码-

    var replacedStr = str.replace(/[^a-zA-Z0-9'.-\[\], ]/g,"#");

Output for various values of str are - 各种str值的输出是-

   str = "hello_";
   replacedStr is hello#
   _______________________
   str = "hello@_";
   replacedStr is hello@#

I wanted to know why '@' isnot being replaced from above regex. 我想知道为什么不在正则表达式中替换“ @”。

The same behavior is with characters - underScore, question-Mark, Angular brackets. 字符的行为相同-underScore,问号和尖括号。

Please guide. 请指导。

Thanks, 谢谢,

Vibhav 维巴夫

In your original regex, your dash (hyphen) is being interpreted as a range: 在原始正则表达式中,破折号(连字符)被解释为一个范围:

[^a-zA-Z0-9'.-\[\], ]

This is being intepreted as the range of characters from dot . 这被解释为点的字符范围. until opening bracket [ , which includes the at symbol. 直到打开括号[ ,其中包括 at符号。 If you move the hyphen to the very end of the negated character class, the regex will work as intended: 如果将连字符移动到否定字符类的最后,则正则表达式将按预期工作:

 str = "hello@_"; str = str.replace(/[^a-zA-Z0-9'.\\[\\], -]/g,"#"); console.log(str); 

Couple of mistakes in your reg-ex you have to put '-' in front of charachter class (or at last). 正则表达式中有几个错误,您必须在字符类前面(或最后)加上“-”。

Below reg-ex will do the trick 下面的正则表达式可以解决问题

/[^.,\[\]\\'a-zA-Z0-9]/g

you can use online testers like http://www.regexpal.com/ to check regex's 您可以使用http://www.regexpal.com/等在线测试仪来检查regex的

连字符将作为范围,因此您需要向其添加一个转义序列。

str.replace(/[^a-zA-Z0-9'.\-\[\]]/g,"#");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM