Regex not allowing certain special characters

后端 未结 1 1773
一生所求
一生所求 2021-01-04 21:23

I have the following regex which does not allow certain special characters:

if (testString.match(/[`~,.<>;\':\"\\/\\[\\]\\|{}()-=_+]/)){    
    alert(         


        
相关标签:
1条回答
  • 2021-01-04 22:30

    You've got a character range in there: )-= which includes all ASCII characters between ) and = (including numbers). Move the - to the end of the class or escape it:

    /[`~,.<>;':"\/\[\]\|{}()=_+-]/
    

    Also, you don't need to escape all of those characters:

    /[`~,.<>;':"/[\]|{}()=_+-]/
    

    Note that in your case, it is probably enough for you, to use test instead of match:

    if (/[`~,.<>;':"/[\]|{}()=_+-]/.test(testString))){
        ...
    

    test returns a boolean (which is all you need), while match returns an array with all capturing groups (which you are discarding anyway).

    Note that, as Daren Thomas points out in a comment, you should rather decide which characters you want to allow. Because the current approach doesn't take care of all sorts of weird Unicode characters, while complaining about some fairly standard ones like _. To create a whitelist, you can simply invert both the character class and the condition:

    if (!/[^a-zA-Z0-9]/.test(testString)) {
       ...
    

    And include all the characters you do want to allow.

    0 讨论(0)
提交回复
热议问题