Localization in JavaScript. Code examples open

Localization in JavaScript. Code examples

The introduction of the ES2021 standard has added built-in localization capabilities to the JavaScript language. These possibilities are presented
mainly the following items:

Intl.ListFormat – used to format lists
Intl.DisplayNames – used to format some names
Intl.DateTimeFormat – used to format dates and times
Intl.NumberFormat – used to format numbers

Intl.ListFormat – list localization

The Intl.ListFormat object allows you to format lists according to some localization settings. His
The constructor can take two parameters:

The locales parameter represents a language code in BCP 47 format or a set of locale codes.
The options parameter represents an additional set of options:

  • localeMatcher – matching algorithm. It can take two values: “lookup” and “best fit“. The default value is “best fit“.
  • style – the length of the string to be formatted. Possible values: “long” (for example, A, B, and C), “short” or “narrow
    (for example, A, B, C). The default value is “long
  • type – output string format. Possible values: “conjunction” (the penultimate and last element in the list
    are connected by the union “and” (“and”) – A, B and C), “disjunction” (the penultimate and last elements in the list
    are connected by the union “or” (“or”) – A, B or C), “unit” (used for lists with numeric values and adds units of measure to them). The default value is “conjunction

To format a list, this object provides the format() method. Which the formatted list is passed. The method returns a formatted localized list as a string.

Let’s look at a few examples. Let’s add the union “And“:

    const users = ["Alexander", "Timote", "Sergey"];

    const newusers = new Intl.ListFormat("ru").format(people); // , { style:"long", type: "conjunction" }
    console.log(newusers);   // Alexander, Timote и Sergey

You can apply your settings:

    Intl.ListFormat("ru", { style: "long", type: "conjunction" });

Now we use the union “or”:

    const user = ["Alexander", "Timote", "Sergey"];
    const users = new Intl.ListFormat("ru", { style: "short", type: "disjunction" }).format(people);
    console.log(users);// Alexander, Timote или Sergey

Other examples:

    const users = ["Alexander", "Timote", "Sergey"];

    // English language
    const enUsers = new Intl.ListFormat("en", { style: "long", type: "conjunction" }).format(users);
    console.log(enUsers);    // Alexander, Timote, and Sergey

    // German language
    const deUsers = new Intl.ListFormat("de", { style: "long", type: "conjunction" }).format(users);
    console.log(deUsers);    // Alexander, Timote und Sergey

    // French language
    const frUsers = new Intl.ListFormat("fr", { style: "long", type: "conjunction" }).format(users);
    console.log(frUsers);    // Alexander, Timote et Sergey

    // Chinese
    const zhUsers = new Intl.ListFormat("zh", { style: "long", type: "conjunction" }).format(users);
    console.log(zhUsers);    // Alexander、Timote和Sergey

Date and time localization

JavaScript uses the Intl.DateTimeFormat object to localize dates and times. Its constructor can take two parameters:

    Intl.DateTimeFormat([locales[, options]])

The locales parameter represents a language code in BCP 47 format or a set of locale codes. The options parameter represents an additional set of options:
The options parameter represents an additional set of options

  • dateStyle – defines the date formatting style. Possible values: “full”, “long”, “medium”, “short”
  • timeStyle – defines the time formatting style.
    Possible values: “full“, “long“, “medium“, “short
  • calendar – sets the calendar. Possible values: “buddhist”, “chinese”, ” coptic”, “ethiopia”, “ethiopic”, “gregory”, ” hebrew”, “indian”, “islamic”, “iso8601”, “japanese”, “persian”, “roc”
  • numberingSystem – specifies the number system to use. Possible values: “arab”, “arabext”, ” bali”, “beng”, “deva”, “fullwide”, ” gujr”, “guru”, “hanidec”, “khmr”, ” knda”, “laoo”, “latn”, “limb”, “mlym”, ” mong”, “mymr”, “orya”, “tamldec”, ” telu”, “thai”, “tibt”
  • dayPeriod – day period format. Possible values: “narrow”, “short”, ” long”.
  • timeZone – time zoneа.
  • hour12 – indicates whether the 12-hour format (value true) or 24-hour format will be used
  • hourCycle – hourly cycle. Possible values: “h11”, “h12”, “h23”, “h24”
  • formatMatcher – sets the date/time format matching algorithm. Possible values: “basic” and “best fit”
  • weekday – specifies the format for the day of the week. Possible values:
    long” (e.g. Thursday)
    short” (for example, Thu)
    narrow” (for example, T is short for Thursday)
  • era – defines the era output format. Possible values:
    “long” (e.g. Anno Domini)
    “short” (for example AD)
    “narrow” (for example, A)
  • year – specifies the year format. Possible values:
    “numeric” (full number, e.g. 2021)
    “2-digit” (prints only the last two digits)
  • month – defines the format of the month. Possible values:
    numeric” (example, 2)
    2-digit” (in the form of a two-digit code, for example – 02)
    long” (example, March)
    short” (example, Mar)
    narrow” (example, M)
  • day – determines how the day number is displayed. Possible values:
    numeric” (e.g. 2)
    2-digit” (in the form of a two-digit code, for example, 02)
  • hour – sets the output format for the hour. Possible values: “numeric” and “2-digit
  • minute – sets the output format of the minute. Possible values: “numeric” and “2-digit
  • second – sets the output format of the second. Possible values: “numeric” and “2-digit
  • fractionalSecondDigits – determines the output format for fractional seconds. Possible values:
    0 (fractions of a second are not displayed)
    1 (only the first digit of a fraction of a second is displayed, for example, a value of 736 displays 7)
    2 (only the first two digits of a fraction of a second are displayed, for example, with a value of 736, 73 is displayed)
    3 (three digits of a fraction of a second are displayed, for example, a value of 736 displays 736)
  • timeZoneName: defines the representation of the name of the time zone. Possible values:
    long” (full name, e.g., “Pacific Standard Time, Nordamerikanische Westküsten-Normalzeit”)
    short” (short name, e.g. PST, GMT-8)
    longOffset” (full name in GMT format, e.g. “GMT-8”)
    shortOffset” (short name in GMT format, for example, “GMT-0800”)
    longGeneric“: (full generalized format, e.g.,, “Pacific Time, Nordamerikanische Westküstenzeit”)
    shortGeneric” (short generalized format, e.g., “PT, Los Angeles Zeit”)

For date formatting, the Intl.DateTimeFormat object provides the format() method, which is passed the formatted date – Date object.

    const now = new Date();
    const ruDate = new Intl.DateTimeFormat("ru").format(now);
    console.log(ruDate);    // 12.09.2021
    const enDate = new Intl.DateTimeFormat("en").format(now);
    console.log(enDate);    // 9/12/2021

By default, the format() method returns the date in abbreviated format, that is, by actually applying the {dateStyle: “short”}. With the dateStyle parameter, we can customize the output of the date.

Let’s see what options for displaying dates the Intl.DateTimeFormat object provides us using the example of the Russian-speaking culture:

    const now = new Date();
    const shortDate = new Intl.DateTimeFormat("ru", { dateStyle: "short" }).format(now);
    console.log(shortDate);     // 12.09.2021
    const mediumDate = new Intl.DateTimeFormat("ru", { dateStyle: "medium" }).format(now);
    console.log(mediumDate);    // 12 сент. 2021 г.
    const longDate = new Intl.DateTimeFormat("ru", { dateStyle: "long" }).format(now);
    console.log(longDate);      // 12 сентября 2021 г.
    const fullDate = new Intl.DateTimeFormat("ru", { dateStyle: "full" }).format(now);
    console.log(fullDate);      // воскресенье, 12 сентября 2021 г.
</js]

By default, the <em>format()</em> method does not output the time. Using the timeStyle parameter, we will configure the output of time using the examplecRussian-speaking culture:

[js]
    const now = new Date();
    const shortTime = new Intl.DateTimeFormat("ru", { timeStyle: "short" }).format(now);
    console.log(shortTime);     // 20:42
    const mediumTime = new Intl.DateTimeFormat("ru", { timeStyle: "medium" }).format(now);
    console.log(mediumTime);    // 20:42:08
    const longTime = new Intl.DateTimeFormat("ru", { timeStyle: "long" }).format(now);
    console.log(longTime);      // 20:42:08 GMT+11
    const fullTime = new Intl.DateTimeFormat("ru", { timeStyle: "full" }).format(now);
    console.log(fullTime);      // 20:42:08 GMT+11:00

To return both date and time, both settings must be set:

    const now = new Date();
    const shortDateTime = new Intl.DateTimeFormat("ru", { dateStyle: "short", timeStyle: "short" }).format(now);
    console.log(shortDateTime);     // 12.09.2021, 20:43

Localization of names and Intl.DisplayNames

The Intl.DisplayNames object allows you to localize names, in particular, the names of countries and regions, languages, and some other names. Its constructor can take two parameters:

    Intl.DisplayNames([locales[, options]])

The locales parameter represents a language code in BCP 47 format or a set of locale codes.
The options parameter represents an additional set of options:

  • localeMatcher – matching algorithm. It can take two values: “lookup” and “best fit“.
  • style: the length of the string to be formatted. Possible values are “long“, “short“, and “narrow“. The default value is “long
  • type: the type of titles to be localized. Possible values: “language”: returns the name of the language
    “language”: returns the name of the language
    “region”: returns the name of the country/region
    “script”: returns the name of the written script
    “currency”: returns the name of the currency
  • fallback – specifies an alternative. Possible values are “code” and “none“. “code” specifies a code that specifies the name to be localized.

Which name will be localized is set using the of() method:

    const USAInEnglish = new Intl.DisplayNames("en", { type: "region" }).of("US");
    const USAInRussian = new Intl.DisplayNames("ru", { type: "region" }).of("US");

    console.log(USAInEnglish);  // United States
    console.log(USAInRussian);  // Соединенные Штаты

Constant USAInRussian also receives the name of the country by the code “US”, only in Russian

To get the name of the region (this can be the name of a country or the name of a geographical region), use
parameter type: “region“.

To get the name of the region, the code of the region is passed to the of() method.
The region code can be a two-letter ISO-3166 code (for example, US, RU, DE, etc.) or a three-digit UN code
M49.

For example, use the code “DE” to get the name of Germany in different languages:

    const GermanyInEnglish = new Intl.DisplayNames("en", { type: "region" }).of("DE");
    const GermanyInRussian = new Intl.DisplayNames("ru", { type: "region" }).of("DE");
    const GermanyInGerman = new Intl.DisplayNames("de", { type: "region" }).of("DE");

    console.log(GermanyInEnglish);  // Germany
    console.log(GermanyInRussian);  // Германия
    console.log(GermanyInGerman);   // Deutschland

The value type: “script” is used to get the name of the written script. To get the name of the script in
the of() method is passed a four-letter ISO-15924 code.

The type: “language” value is used to get the name of the language, and the language code is passed to the of() method in the format
languageCode[-scriptCode][-regionCode](-variant), where the languageCode component represents a two-letter ISO 639-1 language code or a three-letter ISO 639-2 code.

    const enRussian = new Intl.DisplayNames("en", { type: "language" }).of("ru");
    const ruRussian = new Intl.DisplayNames("ru", { type: "language" }).of("ru");
    const deRussian = new Intl.DisplayNames("de", { type: "language" }).of("ru");

    console.log(enRussian); // Russian
    console.log(ruRussian); // русский
    console.log(deRussian); // Russisch

Use the language code along with the region code:

    const ruLang = new Intl.DisplayNames("ru", { type: "language" });
    const enUS = ruLang.of("en-US");
    const enGB = ruLang.of("en-GB");

    console.log(enUS);  // american english
    console.log(enGB);  // british english

The value type: “currency” is used to get the name of the currency, and the three-letter ISO4217 code is passed to the of() method. For example:

    const ruLang = new Intl.DisplayNames("ru", { type: "currency" });
    const usd = ruLang.of("USD");
    const euro = ruLang.of("EUR");
    const ruble = ruLang.of("RUB");

    console.log(usd);       // U.S. dollar
    console.log(euro);      // Euro
    console.log(ruble); // Russian ruble

Number Formatting

Different cultures use different approaches to displaying numbers. For example, in some cultures (in particular, in the USA, United Kingdom) the decimal separator is a period, while other cultures use a comma.

Similarly, a period or a comma can serve as a separator between digits. the Intl.NumberFormat object allows us to localize numerals to the desired culture

The Intl.NumberFormat constructor can take two parameters:

    Intl.NumberFormat([locales[, options]])

The locales parameter represents a language code in BCP 47 format or a set of locale codes.

The options parameter represents an additional set of options:

  • localeMatcher – matching algorithm. It can take two values: “lookup” and “best fit“. Default value – “best fit“.
  • compactDisplay – applies if notation is “compact“. Possible values: “long” и “short” (default value)
  • currency – specifies the currency that is used for formatting. Accepts a currency code in ISO4217 format as a value, for example, “USD” (US dollar), “EUR” (euro), etc. This parameter must be specified if the style parameter is set to “currency”.
  • currencyDisplay: specifies how to display the currency.
    Possible values:
    “symbol”: the currency symbol is applied (e.g. € for Euro). Default value
    “narrowSymbol”: currency abbreviation is used (e.g. “$100” instead of “US$100”)
    “code”: currency code applied
    “name”: the localized name of the currency is applied (example, “dollar”)
  • currencySign – the sign before the numeral that represents the currency. Can take the values “standard” (default value) and “accounting”
  • notation – specifies the type of formatting. Possible values:
    standard“: used to format regular numbers. Default value
    scientific“: returns the order of magnitude for the number being formatted
    engineering“: returns a value in exponential notation
    compact“: The string is used to represent exponential notation
  • numberingSystem: числовая система. Возможные значения: “arab”, “arabext”, ” bali”, “beng”, “deva”, “fullwide”, ”
    gujr”, “guru”, “hanidec”, “khmr”, ” knda”, “laoo”, “latn”, “limb”, “mlym”, ” mong”, “mymr”, “orya”, “tamldec”, ”
    telu”, “thai”, “tibt”
  • signDisplay: specifies whether to display a sign before the number. Possible values:

    auto“: the sign is displayed only for negative numbers. Default value

    never“: зsign is never shown

    always“: sign is never shown

    exceptZero“: the sign is displayed for all numbers except zero

  • style: formatting type. Possible values:

    “decimal”: to format regular numbers. Default value

    “currency”: for currency formatting

    “percent”: to format percentages

    “unit”: to format units

  • unit: sets the unit of measure. The units of measure used can be found in the following table.
    https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier
  • unitDisplay: display type of units of measure. Possible values:

    “long”: full form (for example, 16 liters)

    “short”: abbreviated form (for example, 16 l). Default value

    “narrow”: compressed form (e.g. 16l)

  • useGrouping: specifies whether to use a separator for the digits of the number. Can be true (use delimiters – default) or false (do not use delimiters)

  • minimumIntegerDigits: the minimum number of digits in a number. Possible values: from 1 (default value) to 21
  • minimumFractionDigits: the minimum number of digits in the fractional part of a number. Possible values: 0 (default) to 20
  • maximumFractionDigits: the maximum number of digits in the fractional part of the number. Possible values: from 0 to 20

  • minimumSignificantDigits: the minimum number of digits in an integer part of a number. Possible values: from 1 (default value) to 21
  • maximumSignificantDigits: the maximum number of digits in the integer part of the number. Possible values: from 1 (default value) to 21

To format a number, the Intl.NumberFormat object provides the format() method, which is passed the number to be formatted and which returns the formatted number as a string.

Let’s localize the number 12500.24 into different languages:

    const amount = 5500.67;

    const en = new Intl.NumberFormat("en").format(amount);
    const ru = new Intl.NumberFormat("ru").format(amount);
    const de = new Intl.NumberFormat("de").format(amount);

    console.log(en);    // 5,500.67
    console.log(ru);    // 5 500,67
    console.log(de);    // 5.500,67

The default number formatting is {style: “decimal”}. We could also apply it explicitly:

    const amount = 5500.67;

    const ru = new Intl.NumberFormat("ru", { style: "decimal" }).format(amount);
  //Intl.NumberFormat("ru").format(amount);

    console.log(ru);    // 5 500,67

Percent Formatting

    const value = 0.851;

    const en = new Intl.NumberFormat("en", { style: "percent" }).format(value);
    const ru = new Intl.NumberFormat("ru", { style: "percent" }).format(value);
    const tr = new Intl.NumberFormat("tr", { style: "percent" }).format(value);

    console.log(en);    // 85%
    console.log(ru);    // 85 %
    console.log(tr);    // %85

However, in the example above, we see that the fractional part is lost. To fix this, we can use the minimumFractionDigits parameter, which sets the number of fractional digits:

    const value = 0.851;

    const en = new Intl.NumberFormat("en", { style: "percent", minimumFractionDigits: 2 }).format(value);
    const ru = new Intl.NumberFormat("ru", { style: "percent", minimumFractionDigits: 2 }).format(value);

    console.log(en);    // 85.10%
    console.log(ru);    // 85,10 %

Currency Formatting

To format the currency, the style: “currency” parameter is used, and the currency parameter must also be specified, to which the currency code is passed:

    const value = 85.1;

    const en = new Intl.NumberFormat("en", { style: "currency", currency: "USD" }).format(value);
    const ru = new Intl.NumberFormat("ru", { style: "currency", currency: "USD" }).format(value);
    const tr = new Intl.NumberFormat("tr", { style: "currency", currency: "USD" }).format(value);

    console.log(en);    // $85.10
    console.log(ru);    // 85,10 $
    console.log(tr);    // $85,10

Withdrawal of multiple currencies:

    const value = 85.1;

    const usd = new Intl.NumberFormat("ru", { style: "currency", currency: "USD" }).format(value);
    const euro = new Intl.NumberFormat("ru", { style: "currency", currency: "EUR" }).format(value);
    const rub = new Intl.NumberFormat("ru", { style: "currency", currency: "RUB" }).format(value);

    console.log(usd);   // 85,10 $
    console.log(euro);  // 85,10 €
    console.log(rub);   // 85,10 ₽

By default, the currency symbol is displayed, but currencyDisplay: “name” allows you to display the localized name of the currency.

Formatting Units

The value of style: “unit” is used to format units of measure. In this case, it is also necessary to specify the name of the unit of measure using the unit parameter:

    const value = 85;

    const en = new Intl.NumberFormat("en", { style: "unit", unit: "liter" }).format(value);
    const ru = new Intl.NumberFormat("ru", { style: "unit", unit: "liter" }).format(value);
    const zh = new Intl.NumberFormat("zh", { style: "unit", unit: "liter" }).format(value);

    console.log(en);    // 85 L
    console.log(ru);    // 85 л
    console.log(zh);    // 85升

By default, the abbreviated form of the currency name is used. With the value unit Display: “long” you can set the display of the full name

    const value = 85;

    const kilobyte = new Intl.NumberFormat("ru", { style: "unit", unit: "kilobyte", unitDisplay: "long" }).format(value);
    const meter = new Intl.NumberFormat("ru", { style: "unit", unit: "meter", unitDisplay: "long" }).format(value);
    const gram = new Intl.NumberFormat("ru", { style: "unit", unit: "gram", unitDisplay: "long" }).format(value);

    console.log(kilobyte);  // 85 килобайт
    console.log(meter);     // 85 метров
    console.log(gram);      // 85 грамм
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*