Pemformatan Alamat dalam JavaScript

WBOY
Lepaskan: 2024-08-06 01:15:52
asal
1051 orang telah melayarinya

Address Formatting in JavaScript

Alamat adalah bahagian asas dalam kehidupan seharian kita, sama ada kita menghantar mel, memesan pakej atau menavigasi ke lokasi baharu. Tetapi apabila mengendalikan alamat dalam kod, perkara boleh menjadi rumit. Negara yang berbeza mempunyai format alamat yang unik, malah dalam satu negara, mungkin terdapat variasi dalam cara alamat distrukturkan. Dalam panduan ini, kami akan meneroka asas pemformatan alamat dan melihat beberapa teknik untuk mengendalikan alamat dalam JavaScript.

Memahami Struktur Alamat Seluruh Dunia

Apabila anda membina apl yang berkaitan dengan alamat, anda perlu bersedia menghadapi dunia yang kompleks. Alamat mungkin kelihatan mudah—hanya beberapa baris teks yang memberitahu pembawa mel ke mana hendak pergi, bukan? Tetapi apabila anda menyelami seluk beluk cara alamat distrukturkan di seluruh dunia, anda akan mendapati bahawa terdapat lebih banyak perkara daripada yang dapat dilihat.

Komponen Alamat Asas

Pada asasnya, alamat terdiri daripada beberapa komponen utama:

  1. Alamat Jalan: Ini nombor rumah dan nama jalan anda. Fikirkan "123 Main Street." Ia adalah roti dan mentega di mana-mana alamat, memberitahu seseorang dengan tepat di mana anda berada di jalan itu.

  2. Bandar/Bandar: Seterusnya ialah nama bandar atau bandar, komuniti tempat alamat anda berada. Ia membantu mengecilkan carian daripada skala global atau nasional kepada sesuatu yang lebih tempatan.

  3. Negeri/Wilayah/Wilayah: Bergantung pada negara, ini boleh menjadi negeri, wilayah atau wilayah. Di A.S., anda akan memasukkan negeri (seperti I.L. untuk Illinois); di U.K., anda mungkin menggunakan nama daerah.

  4. Kod Pos/Kod Pos: Siri nombor kecil yang berguna ini (dan kadangkala huruf) adalah penting untuk perkhidmatan pos mengenal pasti kawasan umum alamat dengan cepat. Ia seperti kod rahsia yang mempercepatkan proses penghantaran.

  5. Negara: Akhir sekali, nama negara memberitahu anda bahagian dunia mana alamat ini. Ia penting untuk mel antarabangsa dan memastikan bahawa surat anda tidak berakhir di seberang planet ini.

Variasi Serantau

Sekarang, di sinilah perkara menjadi menarik. Walaupun komponen alamat kelihatan universal, cara ia disusun dan diformat berbeza dengan ketara dari satu tempat ke satu tempat.

  • Amerika Syarikat: Di A.S., alamat biasanya mengikut format alamat jalan, bandar, negeri dan poskod, semuanya dalam satu pakej kemas.

Contohnya:

123 Main Street
Springfield, IL 62704
USA
Salin selepas log masuk
Salin selepas log masuk
  • United Kingdom: Menyeberangi kolam ke U.K., dan anda akan melihat bahawa poskod diutamakan, dan selalunya terdapat lebih banyak penekanan pada bandar dan daerah. Contohnya:

    10 Downing Street
    London SW1A 2AA
    England
    
    Salin selepas log masuk
  • Jepun: Perkara menjadi terbalik di kepala mereka di Jepun. Alamat bermula dengan kawasan geografi terbesar (wilayah), kemudian zum masuk ke bandar, daerah, dan akhirnya nombor bangunan:

    〒100-0001
    東京都千代田区千代田1-1
    Japan
    
    Salin selepas log masuk
  • Jerman: Di Jerman, poskod mendahului nama bandar dan nombor rumah selalunya mengikut nama jalan:

    Hauptstraße 5
    10115 Berlin
    Germany
    
    Salin selepas log masuk

Variasi serantau ini hanyalah puncak gunung ais. Sesetengah negara termasuk kawasan pentadbiran, manakala yang lain mungkin melangkau komponen tertentu sepenuhnya. Kod anda perlu cukup pintar untuk menyesuaikan diri dengan format ini, memastikan setiap alamat dipaparkan dengan betul, tidak kira dari mana pun ia berasal.

Pemformatan Alamat dalam JavaScript

Jadi, anda mempunyai semua bahagian alamat, tetapi bagaimana anda menyusunnya? Terdapat beberapa cara untuk memformat alamat dalam JavaScript, daripada manipulasi rentetan mudah kepada menggunakan perpustakaan khusus. Mari selami beberapa contoh yang akan membuatkan kod anda menyanyi!

Menggunakan Literal Template

Kaedah pertama ialah menggunakan literal templat. Ia adalah cara yang sangat mudah dan boleh dibaca untuk menggabungkan komponen alamat anda menjadi rentetan yang diformat dengan baik. Begini cara anda boleh melakukannya:

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);
Salin selepas log masuk

Apabila anda menjalankan kod ini, ia akan mencetak:

123 Main Street
Springfield, IL 62704
USA
Salin selepas log masuk
Salin selepas log masuk

Pendekatan ini berfungsi dengan baik apabila anda mempunyai semua komponen, tetapi bagaimana jika beberapa perlu ditambah? Anda mungkin mahu menambah sedikit lagi logik untuk itu.

Mengendalikan Komponen Pilihan

Kadangkala, alamat tidak mempunyai semua medan yang diisi—mungkin anda tidak mempunyai negeri atau poskod. Anda boleh menggunakan semakan bersyarat untuk mengendalikan kes ini:

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);
Salin selepas log masuk

Kod ini dengan anggun mengendalikan komponen yang hilang dengan menyemak sama ada ia wujud sebelum menambahkannya pada alamat yang diformatkan.

Jika anda menjalankan ini, ia akan mengeluarkan:

221B Baker Street
London NW1 6XE
UK
Salin selepas log masuk

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));
Salin selepas log masuk

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
Salin selepas log masuk

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);
Salin selepas log masuk

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());
Salin selepas log masuk

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);
Salin selepas log masuk

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);
    });
Salin selepas log masuk

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');
}
Salin selepas log masuk

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);
    });
Salin selepas log masuk

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!

Atas ialah kandungan terperinci Pemformatan Alamat dalam JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!