>  기사  >  웹 프론트엔드  >  JavaScript의 주소 형식

JavaScript의 주소 형식

WBOY
WBOY원래의
2024-08-06 01:15:521052검색

Address Formatting in JavaScript

우편물을 보내거나, 택배를 주문하거나, 새로운 장소로 이동하는 등 주소는 우리 일상생활의 기본적인 부분입니다. 그러나 코드에서 주소를 처리할 때 상황이 까다로울 수 있습니다. 국가마다 고유한 주소 형식이 있으며, 단일 국가 내에서도 주소 구성 방식이 다를 수 있습니다. 이 가이드에서는 주소 형식의 기본 사항을 살펴보고 JavaScript에서 주소를 처리하는 몇 가지 기술을 살펴보겠습니다.

전세계 주소 구조 이해

주소를 처리하는 앱을 구축할 때는 복잡한 세상에 대비해야 합니다. 주소는 간단해 보일 수 있습니다. 우편배달원에게 어디로 가야 하는지 알려주는 몇 줄의 텍스트만 있으면 됩니다. 그렇죠? 그러나 전 세계적으로 주소가 어떻게 구성되어 있는지에 대한 핵심을 살펴보면 눈에 보이는 것보다 더 많은 것이 있다는 것을 금방 알게 될 것입니다.

기본 주소 구성 요소

주소는 기본적으로 몇 가지 주요 구성 요소로 구성됩니다.

  1. 거리 주소: 집 번호와 거리 이름입니다. "123 Main Street"를 생각해 보세요. 어느 주소에서든 자신이 있는 거리의 정확한 위치를 누군가에게 알려주는 것이 가장 중요합니다.

  2. 시/군: 다음은 시 또는 군 이름, 주소가 위치한 커뮤니티입니다. 검색 범위를 글로벌 또는 국가 규모에서 보다 지역적인 범위로 좁히는 데 도움이 됩니다.

  3. 시/도/지역: 국가에 따라 주, 도 또는 지역이 될 수 있습니다. 미국에서는 주(예: 일리노이의 I.L.)를 포함합니다. 영국에서는 카운티 이름을 사용할 수도 있습니다.

  4. 우편번호: 이 편리한 일련의 숫자(때로는 문자)는 우편 서비스에서 주소의 대략적인 지역을 신속하게 식별하는 데 매우 중요합니다. 배송 속도를 높여주는 비밀코드와 같습니다.

  5. 국가: 마지막으로 중요한 것은 국가 이름을 통해 이 주소가 세계 어느 지역에 속해 있는지 알 수 있습니다. 이는 국제 우편에 꼭 필요한 것이며 귀하의 편지가 지구 반대편으로 도착하지 않도록 보장합니다.

지역적 변형

이제 흥미로운 점이 있습니다. 주소의 구성 요소는 보편적인 것처럼 보이지만 배열 및 형식은 장소에 따라 크게 다릅니다.

  • 미국: 미국의 주소는 일반적으로 거리 주소, 시, 주, 우편번호 형식을 따르며 모두 하나의 깔끔한 패키지로 제공됩니다.

예:

123 Main Street
Springfield, IL 62704
USA
  • 영국: 영국으로 건너가면 우편번호가 먼저 오고 도시와 카운티가 더 강조되는 경우가 많습니다. 예를 들면 다음과 같습니다.

    10 Downing Street
    London SW1A 2AA
    England
    
  • 일본: 일본에서는 상황이 뒤집어집니다. 주소는 가장 큰 지리적 영역(현)으로 시작하여 도시, 지구, 마지막으로 건물 번호로 확대됩니다.

    〒100-0001
    東京都千代田区千代田1-1
    Japan
    
  • 독일: 독일에서는 우편번호가 도시 이름 앞에 오고 집 번호가 거리 이름 뒤에 오는 경우가 많습니다.

    Hauptstraße 5
    10115 Berlin
    Germany
    

이러한 지역적 차이는 빙산의 일각에 불과합니다. 일부 국가에는 행정 구역이 포함되어 있는 반면, 다른 국가에서는 특정 구성 요소를 완전히 건너뛸 수도 있습니다. 코드는 이러한 형식에 적응할 수 있을 만큼 스마트해야 하며 모든 주소가 출처에 관계없이 올바르게 표시되도록 해야 합니다.

JavaScript의 주소 형식

주소의 모든 부분을 얻었습니다. 그런데 이를 어떻게 합치나요? 간단한 문자열 조작부터 특수 라이브러리 사용에 이르기까지 JavaScript에서 주소 형식을 지정하는 몇 가지 방법이 있습니다. 귀하의 코드를 흥겹게 만드는 몇 가지 예를 살펴보겠습니다!

템플릿 리터럴 사용

첫 번째 방법은 템플릿 리터럴을 사용하는 것입니다. 이는 주소 구성요소를 형식이 좋은 문자열로 결합하는 매우 쉽고 읽기 쉬운 방법입니다. 방법은 다음과 같습니다.

const address = {
    street: '123 Main Street',
    city: 'Springfield',
    state: 'IL',
    zip: '62704',
    country: 'USA',
};

const formattedAddress = `${address.street}
${address.city}, ${address.state} ${address.zip}
${address.country}`;

console.log(formattedAddress);

이 코드를 실행하면 다음과 같이 인쇄됩니다.

123 Main Street
Springfield, IL 62704
USA

이 접근 방식은 모든 구성 요소가 있을 때 효과적이지만 일부를 추가해야 하는 경우에는 어떻게 됩니까? 이에 대한 논리를 좀 더 추가하고 싶을 수도 있습니다.

선택적 구성 요소 처리

경우에 따라 주소에 모든 필드가 채워지지 않은 경우도 있습니다. 주 또는 우편번호가 없을 수도 있습니다. 조건부 검사를 사용하여 이러한 경우를 처리할 수 있습니다.

const address = {
    street: '221B Baker Street',
    city: 'London',
    postalCode: 'NW1 6XE',
    country: 'UK',
};

let formattedAddress = `${address.street}
${address.city}`;

if (address.state) {
    formattedAddress += `, ${address.state}`;
}

if (address.postalCode) {
    formattedAddress += ` ${address.postalCode}`;
}

formattedAddress += `
${address.country}`;

console.log(formattedAddress);

이 코드는 형식이 지정된 주소에 추가하기 전에 누락된 구성요소가 있는지 확인하여 누락된 구성요소를 적절하게 처리합니다.

이것을 실행하면 다음과 같이 출력됩니다.

221B Baker Street
London NW1 6XE
UK

Using a Formatting Function

You might want to encapsulate your logic in a reusable function for more complex scenarios. Here's an example of a function that formats an address based on the provided components:

function formatAddress(address) {
    const { street, city, state, zip, country } = address;
    return `${street || ''}
${city || ''}${state ? `, ${state}` : ''}${zip ? ` ${zip}` : ''}
${country || ''}`.trim();
}

const address = {
    street: '1600 Pennsylvania Avenue NW',
    city: 'Washington',
    state: 'DC',
    zip: '20500',
    country: 'USA',
};

console.log(formatAddress(address));

This function checks for each component and adds it if present. It also trims any extra whitespace, ensuring your address looks clean and tidy. When you run this code, you'll see:

1600 Pennsylvania Avenue NW
Washington, DC 20500
USA

JavaScript Libraries for Address Formatting

When it comes to formatting addresses, especially for international applications, handling the nuances of various address formats can become a bit of a juggling act. Thankfully, some great JavaScript libraries make this task much easier. Let's take a look at a few of the best ones.

1. @fragaria/address-formatter

The @fragaria/address-formatter library is a robust solution for formatting international postal addresses. It's designed to handle data from sources like OpenStreetMap's Nominatim API, and it can automatically detect and format addresses according to the customs of different countries.

Key Features:

  • Automatic Country Detection: The library can automatically detect the country and format the address accordingly.
  • Customizable Output: You can specify the output format, whether you want the whole country name, an abbreviation, or even an array of address lines.
  • Support for Abbreviations: Common names like "Avenue" or "Road" can be automatically abbreviated to "Ave" or "Rd."

Example:

const addressFormatter = require('@fragaria/address-formatter');

const address = {
    houseNumber: 301,
    road: 'Hamilton Avenue',
    city: 'Palo Alto',
    postcode: 94303,
    state: 'CA',
    country: 'United States of America',
    countryCode: 'US',
};

const formattedAddress = addressFormatter.format(address);
console.log(formattedAddress);

This will format the address according to U.S. standards, handling any variations seamlessly.

2. i18n-postal-address

The i18n-postal-address library is another fantastic option for international address formatting. It allows for region-specific formatting and supports various attributes such as honorifics, company names, and multiple address lines.

Key Features:

  • Region-Specific Formatting: Format addresses according to the region's specific postal standards.
  • Chaining Methods: You can chain methods for setting different address components, making the code cleaner and more readable.
  • Customizable Formats: You can add or modify address formats for different countries.

Example:

const PostalAddress = require('i18n-postal-address');

const myAddress = new PostalAddress();
myAddress
    .setAddress1('1600 Amphitheatre Parkway')
    .setCity('Mountain View')
    .setState('CA')
    .setPostalCode('94043')
    .setCountry('USA');

console.log(myAddress.toString());

This library is highly flexible and is ideal for applications that need to handle a wide variety of address formats.

3. localized-address-format

If you're looking for something lightweight and zero-dependency, localized-address-format might be your go-to. It's based on Google's libaddressinput and offers simple yet effective address formatting for various locales.

Key Features:

  • Zero Dependencies: No external dependencies, making it a lightweight option.
  • Localized Formatting: Formats addresses according to the local script or the Latin script, depending on your needs.
  • Straightforward API: Simple to use with minimal configuration required.

Example:

import { formatAddress } from 'localized-address-format';

const formattedAddress = formatAddress({
    postalCountry: 'US',
    administrativeArea: 'CA',
    locality: 'San Francisco',
    postalCode: '94103',
    addressLines: ['123 Mission St'],
}).join('\n');

console.log(formattedAddress);

This library is perfect if you need something that works out of the box with minimal fuss.

Address Validation

Formatting addresses is one thing, but what about validating them? Ensuring an address is correct and complete is a crucial step in any application dealing with physical mail or deliveries. Fortunately, several tools and services are available to help you validate addresses effectively.

1. Google Maps Geocoding API

Google Maps Geocoding API is a powerful tool that can help you validate and geocode addresses. You can get detailed information about the location by sending a request to the API with an address, including latitude and longitude coordinates. This can be useful for verifying addresses and ensuring that they are accurate.

Example:

const axios = require('axios');

const address = '1600 Amphitheatre Parkway, Mountain View, CA 94043';

axios
    .get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: address,
            key,
        },
    })
    .then((response) => {
        const { results } = response.data;
        if (results.length > 0) {
            const { formatted_address, geometry } = results[0];
            console.log(`Formatted Address: ${formatted_address}`);
            console.log(`Latitude: ${geometry.location.lat}`);
            console.log(`Longitude: ${geometry.location.lng}`);
        } else {
            console.log('Address not found');
        }
    })
    .catch((error) => {
        console.error(error);
    });

This code sends a request to the Google Maps Geocoding API with an address and retrieves the formatted address, latitude, and longitude coordinates.

2. Comprehensive Validation with validator.js

You can use a library like validator.js if you need more comprehensive address validation. It offers a wide range of validation functions, including those for email addresses, URLs, and, of course, addresses. You can use the isPostalCode function to validate postal codes and ensure they match the expected format. Here's an example:

const validator = require('validator');

const postalCode = '94043';

if (validator.isPostalCode(postalCode, 'US')) {
    console.log('Valid postal code');
} else {
    console.log('Invalid postal code');
}

This code validates a U.S. postal code using the isPostalCode function. You can specify the country code to ensure that the postal code matches the expected format for that country.

3. Address Validation Services

You can turn to specialized address validation services like SmartyStreets, Loqate, or Melissa Data for more advanced address validation needs. These services offer real-time address validation, correction, and geocoding capabilities, ensuring your addresses are accurate and deliverable. While these services often come with a cost, they can be invaluable for applications that rely on accurate address data.

Example:

const SmartyStreets = require('smartystreets-api');

const client = SmartyStreets({
    auth: {
        id: 'your-auth-id
        token
    }
});

const address = {
    street: '1600 Amphitheatre Parkway',
    city: 'Mountain View',
    state: 'CA',
    postalCode: '94043',
    country: 'USA'
};

client.validateAddress(address)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.error(error);
    });

This code uses the SmartyStreets API to validate an address and returns detailed information about the address, including any corrections made.

Summary

Address formatting might seem simple, but when dealing with addresses from around the world, things can get complex quickly. By understanding the basic components of an address and the regional variations, you can build more robust applications that easily handle addresses. Whether you're using simple string manipulation or powerful libraries, JavaScript offers a range of tools to help you format addresses effectively. Choose the method that best fits your needs, and start formatting addresses like a pro!

위 내용은 JavaScript의 주소 형식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:- 덤프다음 기사:- 덤프