Question

How can I use regex to extract zip code, city, and state from a string address in JavaScript?

Answer and Explanation

Extracting a zip code, city, and state from a string address using regular expressions (regex) in JavaScript can be achieved with a well-crafted pattern. Here's how you can do it:

1. Understanding the Address Format:

- Addresses can vary, but a common format is: `Street Address, City, State ZIP`. We'll focus on this format, but keep in mind that variations may require adjustments to the regex.

2. Crafting the Regex:

- We'll use a regex that captures the city, state (using a two-letter abbreviation), and zip code. The regex will look something like this: /([^,]+),\s([A-Z]{2})\s(\d{5}(-\d{4})?)$/

- Let's break it down:

- ([^,]+): Captures the city name (any characters that are not a comma).

- ,\s: Matches a comma followed by zero or more spaces.

- ([A-Z]{2}): Captures the state abbreviation (two uppercase letters).

- \s: Matches zero or more spaces.

- (\d{5}(-\d{4})?): Captures the zip code (5 digits, optionally followed by a hyphen and 4 more digits).

- $: Ensures the match occurs at the end of the string.

3. JavaScript Implementation:

- Here's the JavaScript code to extract the information:

function extractAddressInfo(address) {
  const regex = /([^,]+),\s([A-Z]{2})\s(\d{5}(-\d{4})?)$/;
  const match = address.match(regex);
  if (match) {
    return {
      city: match[1].trim(),
      state: match[2],
      zipCode: match[3],
    };
  } else {
    return null; // Or handle the error as needed
  }
}

const addressString = "123 Main St, Anytown, CA 91234";
const addressInfo = extractAddressInfo(addressString);
if (addressInfo) {
  console.log("City:", addressInfo.city); // Output: City: Anytown
  console.log("State:", addressInfo.state); // Output: State: CA
  console.log("Zip Code:", addressInfo.zipCode); // Output: Zip Code: 91234
} else {
  console.log("Address format not recognized.");
}

4. Handling Variations:

- If your addresses have different formats, you may need to adjust the regex. For example, if the state is spelled out, you'd need to modify the state capture group.

5. Error Handling:

- The code includes a basic check to see if the regex matches. You can add more robust error handling as needed.

This approach provides a flexible way to extract address components using regex in JavaScript. Remember to test with various address formats to ensure your regex is robust enough for your needs.

More questions