← 中文资源

简体中文版本

Intl.getCanonicalLocales 规范化标签

用 Intl.getCanonicalLocales 规范化并去重 BCP 47 标签,捕获非法标签,再把结果交给格式化器。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

en-us -> en-US
ZH-hant-tw -> zh-Hant-TW
fr -> fr
not a locale -> invalid
reason: RangeError
deduped: en-US,de-DE
formatter locale: zh-Hant-TW

实现说明

迭代发生在 for (const input of inputs) 内部——循环之外的语句只执行一遍。 inputs、tags、locale 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——reason:、deduped:、formatter locale:。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件用顶层绑定保存自己的状态:inputs、tags、locale。

核心语句

const locale = new Intl.DateTimeFormat('zh-hant-tw').resolvedOptions().locale;
const tags = Intl.getCanonicalLocales(['EN-us', 'en-US', 'de-de']);
const [tag] = Intl.getCanonicalLocales(input);

代码示例

const inputs = ['en-us', 'ZH-hant-tw', 'fr', 'not a locale'];

for (const input of inputs) {
  try {
    const [tag] = Intl.getCanonicalLocales(input);
    console.log(input, '->', tag);
  } catch (error) {
    console.log(input, '-> invalid');
    console.log('reason:', error.name);
  }
}

const tags = Intl.getCanonicalLocales(['EN-us', 'en-US', 'de-de']);
console.log('deduped:', tags.join(','));

const locale = new Intl.DateTimeFormat('zh-hant-tw').resolvedOptions().locale;
console.log('formatter locale:', locale);