Reputation: 3114
I need to check zip codes in JavaScript. The rule is 4 digits are mandatory and 2 letters at the end are optional. 1 space between the digits and the letters is also allowed.
Examples:
1019 //true
1019PZ //true
1019 PZ //true
1019P //false
(and anything else is false)
This is the regular expression I have so far. But in this regex the letters at the end are not optional but mandatory
var regex = /^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{2}$/i;
Any suggestions to make the letters at the end optional?
Upvotes: 0
Views: 555
Reputation: 1162
The following works:
\d{4} ?[A-z]{2}?
Upvotes: 0
Reputation: 240888
Group [a-z]{2}
with a non-capturing group (?:[a-z]{2})?
followed by ?
in order to make the group optional. In doing so, two letters will be optional and you can't have just a single letter.
^[1-9][0-9]{3} ?(?!sa|sd|ss)(?:[a-z]{2})?$
Upvotes: 4
Reputation: 993
For example You can try this one:
/^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{0,2}$/
Just add to a range a value of zero, which means that your letter can be present from zero to two times.
Upvotes: 0