JavaScript でのアドレスの書式設定

WBOY
リリース: 2024-08-06 01:15:52
オリジナル
1050 人が閲覧しました

Address Formatting in JavaScript

住所は、郵便を送る場合でも、荷物を注文する場合でも、新しい場所に移動する場合でも、私たちの日常生活の基本的な部分です。ただし、コードでアドレスを処理する場合、問題が発生する可能性があります。国によっては固有の住所形式があり、同じ国の中でも住所の構造が異なる場合があります。このガイドでは、住所の書式設定の基本を学び、JavaScript で住所を処理するためのいくつかのテクニックを見ていきます。

世界中の住所構造を理解する

住所を扱うアプリを構築するときは、複雑な世界に備える必要があります。住所は単純なように思えるかもしれません。郵便配達員に宛先を伝えるたった数行のテキストだけですよね。しかし、世界中でアドレスがどのように構成されているかの核心を深く掘り下げてみると、見た目以上のものがあることがすぐにわかります。

基本的なアドレスコンポーネント

アドレスの中核は、いくつかの重要なコンポーネントで構成されています。

  1. 番地: これはあなたの番地と番地です。 「メインストリート123」を思い浮かべてください。これはあらゆる住所の基本であり、通りのどこにいるかを正確に誰かに伝えることができます。

  2. 市/町: 次に、住所がある市または町の名前、コミュニティです。検索を世界規模または全国規模からよりローカルなものに絞り込むのに役立ちます。

  3. 州/県/地域: 国によっては、これは州、県、または地域になります。米国では、州を含めます (イリノイ州の I.L. など)。英国では、郡名を使用することがあります。

  4. 郵便番号/郵便番号: この便利な一連の数字 (場合によっては文字) は、郵便サービスが住所の大まかな地域を迅速に識別するために非常に重要です。これは、配送プロセスをスピードアップする秘密のコードのようなものです。

  5. : 最後に重要なことですが、国名によって、この住所が世界のどの地域に属しているかがわかります。これは国際郵便に不可欠であり、手紙が地球の裏側に届くことを防ぎます。

地域ごとの違い

さて、ここからが興味深いことになります。住所の構成要素は普遍的であるように見えますが、その配置と形式は場所によって大きく異なります。

  • 米国: 米国では通常、住所は番地、市区町村、州、郵便番号の形式に従い、すべてが 1 つのきちんとしたパッケージになっています。

例:

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!