I don't need the city or address, just the state. And I don't want to make an API call if possible. The priority is a light-weight solution, ideally just Javascript.
I have a user-input zipcode
, and I want to display a paragraph of text depending on the state that the zipcode is in. I know it's much more complicated to lookup City and State, and for that an API such as the one the USPS exposes is probably best. But to just match state, perhaps on just the first three numbers, the solution (I think) should be easy and lightweight.
Javascript ideally. PHP could also work.
zippopotam.us has a REST API. Here is an example of how to get a State from a ZIP in pure JavaScript (no libraries):
or in jsfiddle if you prefer.
US zipcode data is in fact stable enough that you can do this without hitting an api or a database if only State (not the City or anything else) is needed.
Here's a lightweight JS solution:
Many thanks to the help from @kevin-boucher and @abaldwin99 on parsing smaller New England codes and avoiding the dreaded octal evaluation bug with their answers here.
Also thanks for much of the original code goes to this useful page.
You can return the most likely state for a given zipcode with an array of ranges.
This is not a validator- not every number in a range is actually assigned as a zip code,and there may be new ranges added in the future.
stateFromZip('49125')
/* returned value: (String) Michigan */