國際化(Internationalization,簡稱 i18n,取首尾字母與中間 18 個字)指的是讓軟體能被世界各地、使用各種語言的使用者順利使用的過程。它聽起來抽象,但地雷往往很具體:日期格式寫死了月/日/年、貨幣一律加 $、排序假設所有語言都按字母表來。
function formatDate(d) {
// 大家都用 month/date/year... 對吧?
var month = d.getMonth() + 1;
var date = d.getDate();
var year = d.getFullYear();
return month + "/" + date + "/" + year;
}
function formatMoney(amount) {
// 所有錢都是美元、都帶小數兩位... 對吧?
return "$" + amount.toFixed(2);
}
function sortNames(names) {
// 名字永遠按字母排序... 對吧?
names.sort(function (a, b) {
var left = a.toLowerCase(), right = b.toLowerCase();
if (left > right) return 1;
if (left === right) return 0;
return -1;
});
}
三個註解裡的「對吧?」都是錯的。這正是 i18n 要處理的問題。
傳統做法靠 toLocaleString(),但結果字串把實作的所有細節都打包進去了,你無法指定要哪些欄位。想要的格式也未必對得上,而且挑不了 locale。排序更慘:localeCompare() 存在歸存在,介面卻不適合直接餵給 sort,也不能指定 locale 或排序方式。
結果就是那些真正需要 i18n 的嚴肅應用(例如顯示貨幣的金融網站),只能把資料打包送到伺服器處理完再送回來——就為了格式化一個金額。
新的 Intl 大幅補上了這個空缺。它提供日期、數字格式化與文字排序的能力,locale 可選且支援後退,能指定要包含哪些成分,支援自訂百分比、有效數字與貨幣格式,排序選項也很完整。效能上還做了一件事:locale 與選項的解析只做一次,而非每次操作都重跑。
但要務實看待它的保證。Intl 的設計哲學是「盡力而為」,精確輸出幾乎總是刻意不指定的。實作可以只支援部分 locale,也可以忽略你傳入的格式選項。多數主流瀏覽器的 locale 覆蓋率不錯,但這不是規格保證——在記憶體受限的裝置上尤其如此。
var ctor = "Collator"; // 或 DateTimeFormat、NumberFormat
var instance = new Intl[ctor](locales, options);
locales 可以是單一語言標籤字串,也可以是標籤陣列。標籤形如 en(英語)、de-AT(奧地利德語)、zh-Hant-TW(台灣繁體中文)。標籤後可接 Unicode 擴充: -u-key1-value1-key2-value2。
options 的屬性決定格式化器與排序器的行為,各建構子的解讀不同。
主要選項:weekday 與 era(narrow/short/long)、month(另有 2-digit/numeric)、year、day、hour/minute/second(2-digit 或 numeric)、timeZoneName(short/long)、timeZone。
注意這些值不對應固定格式。narrow/short/long 只是「大約多長」的提示,星期六和星期日都可能是 S。若你不指定 weekday/hour 等欄位,實作會自動補上 year/month/day。另有 hour12 可強制 12 或 24 小時制。
var msPerDay = 24 * 60 * 60 * 1000;
var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));
// 美式:短數字 + 短時區
var americanDateTime = new Intl.DateTimeFormat("en-US", {
year: "2-digit", month: "2-digit", day: "2-digit",
hour: "2-digit", minute: "2-digit", timeZoneName: "short"
}).format;
print(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
// 葡語:完整年份與月份全名,統一轉 UTC
var portugueseTime = new Intl.DateTimeFormat(["pt-BR", "pt-PT"], {
year: "numeric", month: "long", day: "numeric",
hour: "2-digit", minute: "2-digit",
timeZoneName: "short", timeZone: "UTC"
});
print(portugueseTime.format(july172014)); // 17 de julho de 2014 00:00 GMT
// 瑞士:依官方語言使用頻率後退
var swissTime = new Intl.DateTimeFormat(
["de-CH", "fr-CH", "it-CH", "rm-CH"],
{ weekday: "short", hour: "numeric", minute: "numeric",
timeZone: "UTC", timeZoneName: "short" }
).format;
print(swissTime(july172014)); // Do. 00:00 GMT
// 日本年號
var jpYearEra = new Intl.DateTimeFormat("ja-JP-u-ca-japanese",
{ year: "numeric", era: "long" });
print(jpYearEra.format(july172014)); // 平成26年
最後兩個例子展示了 Unicode 擴充的用法:日曆系統的 key 是 ca,數字系統是 nu,所以泰語配中國曆法加泰語數字寫成 th-TH-u-ca-chinese-nu-thai。
主要選項:style(currency/percent/decimal)、currency(三字母代碼,需搭配 currency style)、currencyDisplay(code/symbol/name)、minimumIntegerDigits(1–21)、minimumFractionDigits 與 maximumFractionDigits(0–20)、minimumSignificantDigits 與 maximumSignificantDigits(1–21,會覆蓋整數/小數位設定)、useGrouping(是否加分位符)。
// 中文漢字數字 + 人民幣
var chineseRMB = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
{ style: "currency", currency: "CNY" });
print(chineseRMB.format(1314.25)); // ¥ 一,三一四.二五
// 美國油價:那個古怪的千分位 9
var gasPrice = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD", minimumFractionDigits: 3 });
print(gasPrice.format(5.259)); // $5.259
// 埃及阿拉伯語百分比
var arabicPercent = new Intl.NumberFormat("ar-EG",
{ style: "percent", minimumFractionDigits: 2 }).format;
print(arabicPercent(0.438));
// 巴林第納爾:等於 1000 費爾,所以需要三位小數
var bahrainiDinars = new Intl.NumberFormat("ar-BH",
{ style: "currency", currency: "BHD" });
print(bahrainiDinars.format(3.17));
最後一個例子是個好提醒:貨幣的小數位數不是國際標準,而是各國自己的規定。多數貨幣兩位,有些零位,科威特第納爾與巴林第納爾是三位。這類細節正是 Intl 替你處理的價值。
主要選項:usage(sort 或 search)、sensitivity(base/accent/case/variant)、numeric(是否把字串中的數字當數字比)、caseFirst(upper/lower/false)、ignorePunctuation。
sensitivity 的效果需要具體例子才看得出來。base 只看基本字元,德語裡 a、A、ä 全視為相同;accent 加入重音但忽略大小寫;case 反之;variant 三者全看。
// 德語電話簿排序:變音符展開為 ae、oe
var names = ["Hochberg", "Hönigswald", "Holzman"];
var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
print(names.sort(germanPhonebook.compare).join(", "));
// 德語字典排序:忽略變音符
var germanDictionary = new Intl.Collator("de-DE-u-co-dict");
print(names.sort(germanDictionary.compare).join(", "));
// 依版本號排序:數字要當數字比,大小寫與標點都不計
var firefoxen = ["FireFöx 3.6", "Fire-fox 1.0", "Firefox 29",
"Fírefox 3.5", "Fírefox 18"];
var usVersion = new Intl.Collator("en-US",
{ sensitivity: "base", numeric: true, ignorePunctuation: true });
print(firefoxen.sort(usVersion.compare).join(", "));
// Fire-fox 1.0, Fírefox 3.5, FireFöx 3.6, Fírefox 18, Firefox 29
最後一個例子裡,numeric: true 讓 29 排在 3.6 後面而非前面——少了這個選項,字典序會把 "3.6" 排在 "29" 之前,因為字元 3 小於 2…等等,這正是問題所在。
還有一個實用場景是「模糊搜尋」:把 usage 設為 search、sensitivity 設為 base,就能讓使用者不帶重音、不分大小寫地找到目標。
var navajoLocales = Intl.Collator.supportedLocalesOf(["nv"], { usage: "sort" });
print(navajoLocales.length > 0 ? "支援" : "不支援");
var usedOptions = new Intl.DateTimeFormat("de-XX", { timeZone: "UTC" })
.resolvedOptions();
print(usedOptions.locale); // de(XX 無效,退回 de)
print(usedOptions.timeZone); // UTC
resolvedOptions() 特別有用——它能告訴你實作實際採用了哪些設定,是除錯 locale 問題時最快的路。
ES5 的 toLocaleString 與 localeCompare 過去沒有明確語意,如今已依 Intl 重新定義,會接受相同的 locales 與 options 參數。簡單場景沿用舊寫法無妨,但需要控制力或要重複格式化時,直接用 Intl 建構子更好——因為它能快取解析結果。