Javascript Regular Expression to match 5 or 9 digit zipcode

前端 未结 2 340
耶瑟儿~
耶瑟儿~ 2020-12-16 03:52

I have a similar issue as my recent post but with a zip code validator, I am trying to convert over to a javascript validation process. my script looks like so:



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

    Change your regex to:

    new RegExp("^\\d{5}(-\\d{4})?$")
    
    0 讨论(0)
  • 2020-12-16 04:13

    Add anchors: new RegExp("^\\d{5}(-\\d{4})?$"). This forces the regular expression engine to only accept a match, if it begins at the first character of the string (^) and ends at the end of the string ($) being matched.

    Note, that there might be a typo in the regular expression you hav given in your question: the second \d is missing a backslash.

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