Javascript regex invalid range in character class

后端 未结 2 692
温柔的废话
温柔的废话 2020-12-16 20:47

I\'m using a regex pattern that I got from regexlib to validate relative urls. On their site you can test the pattern to make sure it fits your needs. Everything works great

相关标签:
2条回答
  • 2020-12-16 21:21

    There is no reason to use RegExp constructor here. Just use RegExp literal:

    var urlRegex = /^(?:(?:\.\.\/)|\/)?(?:\w(?:[\w`~!$=;\-\+\.\^\(\)\|\{\}\[\]]|(?:%\d\d))*\w?)?(?:\/\w(?:[\w`~!$=;\-\+\.\^\(\)\|\{\}\[\]]|(?:%\d\d))*\w?)*(?:\?[^#]+)?(?:#[a-z0-9]\w*)?$/g;
                   ^           ^   ^                                                               ^                                                                                     ^
    

    Inside RegExp literal, you just write the regex naturally, except for /, which now needs escaping, since / is used as delimiter in the RegExp literal.

    In character class, ^ has special meaning at the beginning of the character class, - has special meaning in between 2 characters, and \ has special meaning, which is to escape other characters (mainly ^, -, [, ] and \) and also to specify shorthand character classes (\d, \s, \w, ...). [, ] are used as delimiters for character class, so they also have special meaning. (Actually, in JavaScript, only ] has special meaning, and you can specify [ without escaping inside character class). Other than those 5 character listed above, other characters (unless involved in an escape sequence with \) doesn't have any special meaning.

    You can reduce the number of escaping \ with the information above. For ^, unless it is the only character in the character class, you can put it away from the beginning of the character class. For -, you can put it at the end of the character class.

    var urlRegex = /^(?:(?:\.\.\/)|\/)?(?:\w(?:[\w`~!$=;+.^()|{}\[\]-]|(?:%\d\d))*\w?)?(?:\/\w(?:[\w`~!$=;+.^()|{}\[\]-]|(?:%\d\d))*\w?)*(?:\?[^#]+)?(?:#[a-z0-9]\w*)?$/g;
    

    What was changed:

    [\w`~!$=;\-\+\.\^\(\)\|\{\}\[\]]
    [\w`~!$=;+.^()|{}\[\]-]
    
    0 讨论(0)
  • 2020-12-16 21:46

    Either put - at the end or beginning of the character class or use two backslashes to do a regex escape within string

    since you are using string you need to use two backslashes for each special characters..


    NOTE

    Check out this answer on SO which explains when to use single or double backslashes to escape special characters

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