JavaScript Intl API (國際化)

當你的網站需要支援不同國家的使用者時,處理日期、數字、貨幣與時間格式會變得非常繁瑣。JavaScript 內建的 Intl 物件提供了強大的國際化處理能力,讓你不需要再寫複雜的正則表達式或載入大型套件。

數字與貨幣格式化 (NumberFormat)

這在電商網站或金融應用中非常常見,能自動根據地區顯示正確的百分比、貨幣符號與千分位。

// 格式化為台幣
const price = 123456.789;
const twdFormatter = new Intl.NumberFormat('zh-TW', {
  style: 'currency',
  currency: 'TWD',
});

console.log(twdFormatter.format(price)); // "$123,456.79"

// 格式化為日圓 (不顯示小數點)
const jpyFormatter = new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY',
});
console.log(jpyFormatter.format(price)); // "¥123,457"

日期與時間格式化 (DateTimeFormat)

根據地區慣例顯示日期。

const date = new Date();

// 台灣常見格式:2025/1/2
console.log(new Intl.DateTimeFormat('zh-TW').format(date));

// 完整格式化
const fullFormatter = new Intl.DateTimeFormat('zh-TW', {
  dateStyle: 'full',
  timeStyle: 'medium',
});
console.log(fullFormatter.format(date)); // "2025年1月2日 星期四 下午..."

相對時間格式化 (RelativeTimeFormat)

常用於顯示「3 分鐘前」、「昨天」等動態文字。

const rtf = new Intl.RelativeTimeFormat('zh-Hant', { numeric: 'auto' });

console.log(rtf.format(-1, 'day')); // "昨天"
console.log(rtf.format(2, 'hour')); // "2 小時後"
console.log(rtf.format(-5, 'minute')); // "5 分鐘前"

列表格式化 (ListFormat)

自動處理清單中的分隔符號,包含最後一個項目的「和」或「或」。

const list = ['蘋果', '橘子', '香蕉'];
const lf = new Intl.ListFormat('zh-TW', { style: 'long', type: 'conjunction' });

console.log(lf.format(list)); // "蘋果、橘子和香蕉"

顯示名稱 (DisplayNames)

將 ISO 代碼轉換為使用者易讀的語言名稱、國家名稱。

const dn = new Intl.DisplayNames(['zh-Hant'], { type: 'language' });
console.log(dn.of('en-US')); // "英文 (美國)"
console.log(dn.of('ja')); // "日文"

總結

Intl API 是開發高品質全語系應用的秘密武器。它的優點是:

  • 原生支持: 無需下載任何外部庫。
  • 性能優越: 由瀏覽器引擎直接處理。
  • 維護簡便: 自動處理各國複雜的格式化規則。

在 2025 年,如果你還在用字串拼接來處理 "$ 1,000" 或 "1 小時前",那就是時候開始使用 Intl API 了。