如何检查字符串是否只包含Javascript中的特定字符集?

时间:2014-08-09 12:13:00

标签: javascript regex

This问题提供了匹配特殊字符和数字的解决方案 我需要使用哪些正则表达式来匹配Javascript中的一组特殊字符?

例如,我想检查一个字符串是否包含除了特殊字符~!@#$之外的任何内容。

我已尝试过以下代码,但我不确定它是否正确:

var myRegex = \~!@#\;  
var testString = "!!@@ABCD[]";  // This contains [], so it must be false  
if(myRegex.test(testString))  
{  
   //do something  
}  

让我知道downvoting的原因,以便我可以避免将来的错误。 没有任何理由的贬低将无助于我们任何人学习任何东西。感谢。

1 个答案:

答案 0 :(得分:2)

  

我想检查一个字符串是否包含特殊字符other than

之后的任何~!@#$

您可以尝试以下正则表达式

^[^~!@#$]+$

模式说明:

  ^                        the beginning of the line
  [^~!@#$]+                any character except: 
                           '~', '!', '@', '#', '$' 
                           (1 or more times )
  $                        the end of the line

Learn more...关于 character sets

enter image description here