# Regular expression for a zipcode with 4 digits and 2 optional letters

Regular expression for a zipcode with 4 digits and 2 optional letters

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?

## solution

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})?$
```