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

JavaScript 中的地址格式

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

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]刪除
最新教學 更多>
  • 為什麼使用Firefox後退按鈕時JavaScript執行停止?
    為什麼使用Firefox後退按鈕時JavaScript執行停止?
    導航歷史記錄問題:JavaScript使用Firefox Back Back 此行為是由瀏覽器緩存JavaScript資源引起的。 To resolve this issue and ensure scripts execute on subsequent page visits, Firefox...
    程式設計 發佈於2025-02-07
  • 如何使用替換指令在GO MOD中解析模塊路徑差異?
    如何使用替換指令在GO MOD中解析模塊路徑差異?
    克服go mod中的模塊路徑差異 coreos/bbolt:github.com/coreos/ [email受保護]:解析go.mod:模塊將其路徑聲明為:go.etcd.io/bbolt `要解決此問題,您可以在go.mod文件中使用替換指令。只需在go.mod的末尾添加以下行:[&& &...
    程式設計 發佈於2025-02-07
  • 可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    </main> <section> ,但无法使其正常工作,如您所见。任何洞察力都将不胜感激! display:grid; { position:sticky; top:1em; z-index:1 1 ; { { { pos...
    程式設計 發佈於2025-02-07
  • Trie簡介(前綴樹)
    Trie簡介(前綴樹)
    Trie 是一種類似樹的數據結構,用於有效存儲和搜索字符串,尤其是在諸如AutoComplete,Spell Checking和IP路由之類的應用程序中。 Trie的關鍵特性: nodes :每個節點代表一個字符。 :root節點是空的,並用作起點。 :每個節點最多有26個...
    程式設計 發佈於2025-02-07
  • 如何處理PHP MySQL中的分頁和隨機訂購以避免重複和不一致?
    如何處理PHP MySQL中的分頁和隨機訂購以避免重複和不一致?
    [ php mysql分頁與隨機訂購:克服重複和頁面一致性挑戰 1。在後續頁面上排除先前看到的結果,以防止先前顯示的結果在隨機訂購時重新出現在隨機訂購時:在會話變量中存儲ID作為逗號分隔的列表。 修改您的sql查詢以排除這些IDS: 2。確保第一頁上的不同結果隨機訂購將使很難在第一頁上保證獨特的...
    程式設計 發佈於2025-02-07
  • 如何使用PHP從XML文件中有效地檢索屬性值?
    如何使用PHP從XML文件中有效地檢索屬性值?
    從php 您的目標可能是檢索“ varnum”屬性值,其中提取數據的傳統方法可能會使您感到困惑。 - > attributes()為$ attributeName => $ attributeValue){ echo $ attributeName,'=“',$ a...
    程式設計 發佈於2025-02-07
  • 哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    在Python 射線tracing方法Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a路徑對象表示多邊形。它檢查給定點是否位於定義路徑內。 T...
    程式設計 發佈於2025-02-07
  • 為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    [2明確擔心Microsoft Visual C(MSVC)在正確實現兩相模板實例化方面努力努力。該機制的哪些具體方面無法按預期運行? 背景:說明:的初始Syntax檢查在範圍中受到限制。它未能檢查是否存在聲明名稱的存在,導致名稱缺乏正確的聲明時會導致編譯問題。 為了說明這一點,請考慮以下示例:一個...
    程式設計 發佈於2025-02-07
  • 版本5.6.5之前,使用current_timestamp與時間戳列的current_timestamp與時間戳列有什麼限制?
    版本5.6.5之前,使用current_timestamp與時間戳列的current_timestamp與時間戳列有什麼限制?
    在默認值中使用current_timestamp或mysql版本中的current_timestamp或在5.6.5 這種限制源於遺產實現的關注,這些限制需要為Current_timestamp功能提供特定的實現。消息和相關問題 `Productid` int(10)unsigned not ...
    程式設計 發佈於2025-02-07
  • \“(1)vs.(;;):編譯器優化是否消除了性能差異?\”
    \“(1)vs.(;;):編譯器優化是否消除了性能差異?\”
    使用(1)而不是(;;)會導致無限循環的性能差異? 現代編譯器,(1)和(;;)之間沒有性能差異。 是如何實現這些循環的技術分析在編譯器中: perl: S-> 7 8 unstack v-> 4 -e語法ok 在GCC中,兩者都循環到相同的彙編代碼中,如下所示:。 globl t_時 ...
    程式設計 發佈於2025-02-07
  • 大批
    大批
    [2 數組是對象,因此它們在JS中也具有方法。 切片(開始):在新數組中提取部分數組,而無需突變原始數組。 令arr = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    程式設計 發佈於2025-02-07
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決“一般錯誤:2006 MySQL 服務器已消失”介紹:將數據插入MySQL 數據庫有時會導致錯誤“一般錯誤:2006 MySQL 服務器已消失”。當與服務器的連接丟失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變量之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2025-02-07
  • 在映射到MySQL枚舉列時,如何確保冬眠保留值?
    在映射到MySQL枚舉列時,如何確保冬眠保留值?
    在hibernate中保存枚舉值:故障排除錯誤的列type ,他們各自的映射至關重要。在Java中使用枚舉類型時,至關重要的是,建立冬眠的方式如何映射到基礎數據庫。 在您的情況下,您已將MySQL列定義為枚舉,並在Java中創建了相應的枚舉代碼。但是,您遇到以下錯誤:“ MyApp中的錯誤列類型...
    程式設計 發佈於2025-02-07
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript 理解prefix keys primary鍵(movie_id(3))primary鍵(Movie_id) primary鍵(Movie_id) primary鍵(Movie_id) > `這將在整個Movie_ID列上建立標...
    程式設計 發佈於2025-02-07
  • 如何在網站中連接兩個頁面
    如何在網站中連接兩個頁面
    在本指南中,您將學習如何使用基本HTML在網站上鍊接兩個頁面。鏈接頁面允許用戶輕鬆地在網站的不同部分之間導航。讓我們開始吧! 創建兩個HTML文件 首先,創建要鏈接的兩個HTML文件。例如,讓我們創建一個稱為index.html(您的主頁)和另一個稱為.html(您的關於頁面)的名為index....
    程式設計 發佈於2025-02-07

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

Copyright© 2022 湘ICP备2022001581号-3