」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 中的地址格式

JavaScript 中的地址格式

發佈於2024-08-07
瀏覽:354

Address Formatting in JavaScript

Addresses are a fundamental part of our daily lives, whether we're sending mail, ordering packages, or navigating to a new location. But when handling addresses in code, things can get tricky. Different countries have unique address formats, and even within a single country, there can be variations in how addresses are structured. In this guide, we'll explore the basics of address formatting and look at some techniques for handling addresses in JavaScript.

Understanding Address Structures Worldwide

When you're building an app that deals with addresses, you need to be prepared for a world of complexity. Addresses might seem straightforward—just a few lines of text that tell the mail carrier where to go, right? But when you dive into the nitty-gritty of how addresses are structured worldwide, you'll quickly find that there's more to it than meets the eye.

Basic Address Components

At their core, addresses consist of a few key components:

  1. Street Address: This is your house number and street name. Think "123 Main Street." It's the bread and butter of any address, telling someone exactly where on the street you're located.

  2. City/Town: Next up is the city or town name, the community where your address is located. It helps narrow the search down from a global or national scale to something more local.

  3. State/Province/Region: Depending on the country, this could be a state, province, or region. In the U.S., you'd include the state (like I.L. for Illinois); in the U.K., you might use a county name.

  4. Postal Code/Zip Code: This handy little series of numbers (and sometimes letters) is crucial for postal services to quickly identify an address's general area. It's like a secret code that speeds up the delivery process.

  5. Country: Last but certainly not least, the country name tells you which part of the world this address belongs to. It's essential for international mail and ensures that your letter doesn't end up on the other side of the planet.

Regional Variations

Now, here's where things get interesting. While the components of an address seem universal, the way they're arranged and formatted varies significantly from place to place.

  • United States: In the U.S., addresses typically follow the format of street address, city, state, and zip code, all in one tidy package.

For example:

123 Main Street
Springfield, IL 62704
USA
  • United Kingdom: Cross the pond to the U.K., and you'll see that postal codes come first, and there's often more emphasis on the town and county. For instance:

    10 Downing Street
    London SW1A 2AA
    England
    
  • Japan: Things get flipped on their head over in Japan. Addresses start with the largest geographic area (the prefecture), then zoom in to the city, district, and finally the building number:

    〒100-0001
    東京都千代田区千代田1-1
    Japan
    
  • Germany: In Germany, the postal code precedes the city name, and the house number often follows the street name:

    Hauptstraße 5
    10115 Berlin
    Germany
    

These regional variations are just the tip of the iceberg. Some countries include administrative areas, while others might skip specific components entirely. Your code needs to be smart enough to adapt to these formats, ensuring every address is displayed correctly, no matter where it's from.

Address Formatting in JavaScript

So you've got all the pieces of an address, but how do you put them together? There are a few ways to format addresses in JavaScript, ranging from simple string manipulation to using specialized libraries. Let's dive into some examples that'll make your code sing!

Using Template Literals

The first method is to use template literals. They're a super easy and readable way to combine your address components into a nicely formatted string. Here's how you might do it:

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);

When you run this code, it'll print out:

123 Main Street
Springfield, IL 62704
USA

This approach works great when you have all the components, but what if some need to be added? You might want to add a little more logic for that.

Handling Optional Components

Sometimes, addresses don't have all the fields filled in—maybe you don't have a state or a postal code. You can use conditional checks to handle these cases:

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);

This code gracefully handles missing components by checking if they exist before adding them to the formatted address.

If you run this, it will output:

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!

版本聲明 本文轉載於:https://dev.to/ivan_kaminskyi/address-formatting-in-javascript-odc?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何修復 Matplotlib 中的「無顯示名稱且無 $DISPLAY 環境變數」錯誤?
    如何修復 Matplotlib 中的「無顯示名稱且無 $DISPLAY 環境變數」錯誤?
    "_tkinter.TclError: no display name and no $DISPLAY 環境變數"使用Matplotlib 執行Python 腳本時通常會發生此錯誤腳本時通常會發生此錯誤腳本時通常會發生此錯誤在沒有圖形顯示的伺服器上。 Matplotlib 依賴後...
    程式設計 發佈於2024-11-05
  • 您的第一個使用 Node.js 的後端應用程式
    您的第一個使用 Node.js 的後端應用程式
    您是否正在學習 Web 開發並對如何啟動 Node.js 專案感到困惑?別擔心,我有你!我將指導您只需 5 個步驟即可使用 Node.js 和 Express.js 建立您的第一個後端。 ️5個關鍵步驟: 第 1 步:設定項目 第 2 步:整理資料夾 第3步:建立server.js...
    程式設計 發佈於2024-11-05
  • 跨域場景下CORS何時使用預檢請求?
    跨域場景下CORS何時使用預檢請求?
    CORS:了解跨域請求的「預檢」請求跨域資源共享(CORS) 在製作HTTP 時提出了挑戰跨域請求。為了解決這些限制,引入了預檢請求作為解決方法。 預檢請求說明預檢請求是先於實際請求(例如 GET 或 POST)的 OPTIONS 請求)並用於與伺服器協商請求的權限。這些請求包含兩個附加標頭:Acc...
    程式設計 發佈於2024-11-05
  • 如何使用 PHP 的 glob() 函數以副檔名過濾檔案?
    如何使用 PHP 的 glob() 函數以副檔名過濾檔案?
    在 PHP 中以副檔名過濾檔案使用目錄時,通常需要根據副檔名擷取特定檔案。 PHP 提供了一種使用 glob() 函數來完成此任務的有效方法。 若要以副檔名過濾文件,請使用語法:$files = glob('/path/to/directory/*.extension');例如,要檢索目錄/path...
    程式設計 發佈於2024-11-05
  • 理解 JavaScript 中的 Promise 和 Promise Chaining
    理解 JavaScript 中的 Promise 和 Promise Chaining
    什麼是承諾? JavaScript 中的 Promise 就像你對未來做某事的「承諾」。它是一個對象,表示非同步任務的最終完成(或失敗)及其結果值。簡而言之,Promise 充當尚不可用但將來可用的值的佔位符。 承諾國家 Promise 可以存在於以下三種狀態之一...
    程式設計 發佈於2024-11-05
  • 安全分配
    安全分配
    今天,關於 JavaScript 中安全賦值運算子 (?=) 的新提案引起了熱烈討論。我喜歡 JavaScript 隨著時間的推移而不斷改進,但這也是我最近在某些情況下遇到的問題。我應該將快速範例實作作為函數,對吧? 如果您還沒有閱讀該提案,以下是其建議: const [error, value]...
    程式設計 發佈於2024-11-05
  • 建立隊列介面
    建立隊列介面
    建立字元隊列的介面。 需要開發的三個實作: 固定大小的線性隊列。 循環隊列(複用數組空間)。 動態隊列(根據需要成長)。 1 建立一個名為 ICharQ.java 的檔案 // 字元隊列介面。 公共介面 ICharQ { // 向佇列中插入一個字元。 void put(char...
    程式設計 發佈於2024-11-05
  • Pip 的可編輯模式何時對本機 Python 套件開發有用?
    Pip 的可編輯模式何時對本機 Python 套件開發有用?
    使用Pip 在Python 中利用可編輯模式進行本地包開發在Python 的包管理生態系統中,Pip 擁有“- e”(或'--editable') 特定場景的選項。什麼時候使用這個選項比較有利? 答案在於可編輯模式的實現,官方文件中有詳細說明:「從本地以可編輯模式安裝專案(即setu...
    程式設計 發佈於2024-11-05
  • 當您在瀏覽器中輸入 URL 時會發生什麼?
    當您在瀏覽器中輸入 URL 時會發生什麼?
    您是否想知道當您在瀏覽器中輸入 URL 並按 Enter 鍵時幕後會發生什麼?這個過程比您想像的更加複雜,涉及多個步驟,這些步驟無縫地協同工作以提供您請求的網頁。在本文中,我們將探討從輸入 URL 到查看完全載入的網頁的整個過程,闡明使這一切成為可能的技術和協定。 第 1 步:輸入...
    程式設計 發佈於2024-11-05
  • 如何有效管理大量小HashMap物件的「OutOfMemoryError:超出GC開銷限制」?
    如何有效管理大量小HashMap物件的「OutOfMemoryError:超出GC開銷限制」?
    OutOfMemoryError: Handling Garbage Collection OverheadOutOfMemoryError: Handling Garbage Collection Overhead在Java中,當過多時會出現「java.lang.OutOfMemoryError:...
    程式設計 發佈於2024-11-05
  • 為什麼在 Python 列表初始化中使用 [[]] * n 時列表會連結在一起?
    為什麼在 Python 列表初始化中使用 [[]] * n 時列表會連結在一起?
    使用[[]] * n 進行列表初始化時的列表連結問題使用[[]] 初始化列表列表時 n,程式設計師經常會遇到一個意想不到的問題,即列表似乎連結在一起。發生這種情況是因為 [x]n 語法建立對相同基礎清單物件的多個引用,而不是建立不同的清單實例。 為了說明該問題,請考慮以下代碼:x = [[]] * ...
    程式設計 發佈於2024-11-05
  • Python 變得簡單:從初學者到進階 |部落格
    Python 變得簡單:從初學者到進階 |部落格
    Python Course Code Examples This is a Documentation of the python code i used and created , for learning python. Its easy to understand and L...
    程式設計 發佈於2024-11-05
  • 簡化 TypeScript 中的類型縮小和防護
    簡化 TypeScript 中的類型縮小和防護
    Introduction to Narrowing Concept Typescript documentation explains this topic really well. I am not going to copy and paste the same descrip...
    程式設計 發佈於2024-11-05
  • 何時應該使用 session_unset() 而不是 session_destroy() ,反之亦然?
    何時應該使用 session_unset() 而不是 session_destroy() ,反之亦然?
    理解PHP 中session_unset() 和session_destroy() 的區別PHP 函數session_unset() 和session_destroy() 有不同的用途管理會話數據。儘管它們在清除會話變數方面有明顯相似之處,但它們具有不同的效果。 session_unset() 與s...
    程式設計 發佈於2024-11-05
  • 如何選擇在 C++ 中解析 INI 檔案的最佳方法?
    如何選擇在 C++ 中解析 INI 檔案的最佳方法?
    在C 中解析INI 檔案:各種方法指南在C 處理初始化(INI) 檔案時,開發人員經常遇到有效解析這些文件以提取所需資訊的挑戰。本文探討了用 C 解析 INI 檔案的不同方法,討論了它們的優點和注意事項。 本機 Windows API 函數一種方法是利用 Windows API 函數INI 檔案處理...
    程式設計 發佈於2024-11-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3