Intl.getCanonicalLocales Normalizes Tags

Normalize and deduplicate BCP 47 tags with Intl.getCanonicalLocales, catch invalid tags, and feed the result to a formatter.

JavascriptConfig Management

Code

javascriptsnippet
17 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What the code does

The cycling part of this snippet is for (const input of inputs).

Top-level bindings inputs, tags, locale hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (reason:, deduped:, formatter locale:), so every printed line maps back to its originating operation.

Key statements

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);

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `inputs`, `tags`, `locale`.