Javascript Regular Expression to match 5 or 9 digit zipcode
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.
Change your regex to:
new RegExp("^\\d{5}(-\\d{4})?$")