Home > Back-end >  What’s the best way to extract the State code from all types of addresses?
What’s the best way to extract the State code from all types of addresses?

Time:02-18

I’m trying to figure out how to extract the State code from any type of address.

“123 Sunny Dr., Los Angeles, CA 90210, US”
“123 Sunny Lane, Unit B, Los Angeles, CA 90210, USA”
“123 Sunny Ct, Hollywood, CA, USA”
“Los Angeles, CA, US”

For any of these, I would just like the return value to be “CA”

CodePudding user response:

I would use match here with an alternation containing all US state codes:

var addresses = ["123 Sunny Dr., Los Angeles, CA 90210, US", "123 Sunny Lane, Unit B, Los Angeles, CA 90210, USA", "123 Sunny Ct, Hollywood, CA, USA", "Los Angeles, CA, US"];
var states = addresses.map(x => x.match(/\b(?:AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|PR|RI|SC|SD|TN|TX|UT|VT|VA|VI|WA|WV|WI|WY)\b/));
for (var i=0; i < addresses.length;   i) {
    console.log(addresses[i]   " => "   states[i]);
}

We could try to formulate the state code as being a two letter uppercase letter word, but that runs the risk of matching US, which isn't a state code, but rather a country code. A hard-coded alternation works here as there are less than 100 total state/territory codes for the US.

CodePudding user response:

Assuming you're getting just one string, you can

  • create a function that takes a string as an argument
  • split the passed in string on "," into an Array
  • get the second last value in the Array into a variable
  • remove whitespace and numbers, using a regex into another variable
  • return this last variable
  • Related