Intl.getCanonicalLocales Normalizes Tags
Normalize and deduplicate BCP 47 tags with Intl.getCanonicalLocales, catch invalid tags, and feed the result to a formatter.
Code
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-TWWhat 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.