I want to ignore square brackets when using javascript regex

前端 未结 4 1470
我在风中等你
我在风中等你 2021-01-13 13:08

I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the followi

4条回答
  •  粉色の甜心
    2021-01-13 14:04

    Your regex is not in line with what you said:

    I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed

    If you want to accept only those characters, you need to remove the caret:

    var pattern = /^[A-Za-z0-9 "!&,'\\-]+$/;
    

    Notes:

    1. A-z also includesthe characters:

      [\]^_`
      .

      Use A-Za-z or use the i modifier to match only alphabets:

       var pattern = /^[a-z0-9 "!&,'\\-]+$/i;
      
    2. \- is only the character -, because the backslash will act as special character for escaping. Use \\ to allow a backslash.

    3. ^ and $ are anchors, used to match the beginning and end of the string. This ensures that the whole string is matched against the regex.

    4. + is used after the character class to match more than one character.


    If you mean that you want to match characters other than the ones you accept and are using this to prevent the user from entering 'forbidden' characters, then the first note above describes your issue. Use A-Za-z instead of A-z (the second note is also relevant).

提交回复
热议问题