The of() method of Intl.DisplayNames instances receives a code and returns a string based on the locale and options provided when instantiating this Intl.DisplayNames object.
Syntax
of(code)
Parameters
code: The
codeto provide depends on thetype:- If the type is "region",
codeshould be either an two-letter ISO 3166 region code, or a three-digit UN M49 geographic region. It is required to follow theunicode_region_subtaggrammar. - If the type is "script",
codeshould be an four-letter ISO 15924 script code. It is required to follow theunicode_script_subtaggrammar. - If the type is "language",
codeshould be a languageCode ["-" scriptCode] ["-" regionCode ] *("-" variant ) subsequence of theunicode_language_idgrammar. languageCode is either a two-letter ISO 639-1 language code or a three-letter ISO 639-2 language code. - If the type is "currency",
codeshould be a three-letter ISO 4217 currency code. It is required to have exactly three alphabetic characters. - If the type is "dateTimeField",
codeshould be one of:"era","year","quarter","month","weekOfYear","weekday","day","dayPeriod","hour","minute","second","timeZoneName". - If the type is "calendar",
codeshould be a calendar key. It is required to follow thetypegrammar of a Unicode locale identifier.
- If the type is "region",
Return value
A language-specific formatted string, or undefined if there's no data for the input and fallback is "none".
Note:
fallbackis only used ifcodeis structurally valid. See using fallback.
Exceptions
- RangeError
- : Thrown if
codeis not structurally valid for the giventype.
- : Thrown if
Examples
Using the of method
const regionNames = new Intl.DisplayNames("en", { type: "region" });
regionNames.of("419"); // "Latin America"
const languageNames = new Intl.DisplayNames("en", { type: "language" });
languageNames.of("fr"); // "French"
const currencyNames = new Intl.DisplayNames("en", { type: "currency" });
currencyNames.of("EUR"); // "Euro"
Using fallback
When the Intl.DisplayNames is constructed with fallback: "code", the of() method will return the code if the input looks structurally valid but there's no data for the input. If fallback is "none", undefined is returned.
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZL"),
); // "ZL"
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "none" }).of("ZL"),
); // undefined
However, this only applies if the code is structurally valid. For example, if type is "region" but code does not follow the unicode_region_subtag grammar (2 alphabetic characters or 3 numeric characters), a RangeError is directly thrown instead of using the fallback.
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC"),
); // throws RangeError: invalid value "ZLC" for option region