Home > Web Front-end > JS Tutorial > What is the JavaScript Internationalization API (I18n)?

What is the JavaScript Internationalization API (I18n)?

Joseph Gordon-Levitt
Release: 2025-02-10 10:52:09
Original
167 people have browsed it

What is the JavaScript Internationalization API (I18n)?

English is the most widely spoken language in the world, but only one in seven people speak English. It is the first language (native language) of 379 million people, but there are 917 million people who speak Mandarin, 460 million people who speak Spanish, and 341 million people who speak Hindi.

Many non-English speaking users live in emerging markets, with internet growth increasing exponentially. If your web application can be translated globally, your potential target market may increase by 700%!

JavaScript Internationalized API (also known as i18n) allows you to design web pages and applications so that they can easily adapt to the needs of users who speak different languages.

In this article, we will look at the various methods the API provides and how to implement them in your code to reach a wider international audience.

Key Points

  • JavaScript Internationalization API (i18n) promotes the adaptation of web applications to global audiences by supporting various languages ​​and cultural norms.
  • Using Intl objects, developers can format dates, times, numbers, and lists based on local preferences, which may vary by region.
  • The
  • API includes functions such as Intl.DateTimeFormat() and Intl.NumberFormat(), which accept locale identifiers to present information in a format familiar to the user.
  • Advanced features such as relative time formatting (Intl.RelativeTimeFormat) and plural sensitive formatting (Intl.PluralRules) allow for more nuanced and culturally compliant applications.
  • Despite its powerful capabilities, the JavaScript Intl API requires careful implementation to effectively handle language and cultural differences and ensure that applications are truly internationalized.

Internationalization (I18n) can be tricky

Internationalization looks easy… Until you try to do it.

Latin-based languages ​​may be similar on the surface. For example, the form for requesting name, email, and date is translated as follows:

  • Spanish: nombre, email, fecha
  • French: nom, e-mail, date
  • German: name, email, datum

Gettext Internationalization and localization systems have been around for decades, and most programming languages ​​have libraries available.

In a simpler case, you can use some tokenization form. For example, take an HTML template that contains the following:

<code><label> for="name"></label>{{ NAME }}>
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This will dynamically replace "name" when the user sets English as their primary language. Unfortunately, this is where your user interface problems start to appear:

  1. The same language may have different variations. The usage of Spanish in Spain is not exactly the same as in South America.
  2. Words in one language may grow much longer in other languages. For example, "email" is translated in Russian as "электроннное письмо".
  3. Text is not always arranged from left to right. Some are written from right to left – such as Arabic, Hebrew, Kurdish and Yiddish. Other languages ​​can be written from top to bottom, such as Chinese, Korean, Japanese and Taiwanese.

Many issues can be solved by keeping text to a minimum and laying out with CSS properties such as orientation, writing patterns, and logical dimensions.

The term confusion

Further confusion occurs when your application needs to display dates, time, numbers, currency, or units.

Consider displaying the date as "12/03/24". It will be interpreted as:

  • U.S. residents using MDY format will interpret it as "December 3, 2024"
  • Residents of Europe, South America and Asia in DMY format interpreted it as "March 12, 2024",
  • Residents of Canada, China, Japan and Hungary using the more practical YMD format will interpret it as “March 24, 2012”.

(Please note that date separator slashes are not commonly used in all languages!)

The number "1,000" will be interpreted as:

  • People from the United States, Britain, Canada, China and Japan will interpret it as "one thousand",
  • People in Spain, France, Germany and Russia would interpret it as "one (point zero)" because the decimal fractions of these countries are separated by commas.

Even in English alone, the situation can be complicated. The term “1,000 meters” means:

  • 1 km (or 0.62 mi) for U.S. residents
  • For people in the UK, Canada and Australia, it is a collection of a thousand measuring instruments!

JavaScript Intl API

The little-known JavaScript Intl object implements the ECMAScript internationalized API in most modern browsers and runtimes. Support is usually good, and even IE11 has many more useful methods. For older browsers, there is a polyfill and the API can be detected like this:

<code><label> for="name"></label>{{ NAME }}>
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

API is a bit unusual. It provides some object constructors for dates, times, numbers, and lists that pass locales and optional objects containing configuration parameters. For example, this is a DateTime object that specifies American English:

<code>if (window.Intl) {
  // Intl 受支持
}
</code>
Copy after login
Copy after login
Copy after login
Copy after login

This object can be used multiple times to call various methods that pass the Date() value (or available ES6 Temporal). The format method is usually the most practical option. For example:

<code>const dateFormatter = new Intl.DateTimeFormat('en-US');
</code>
Copy after login
Copy after login
Copy after login
Copy after login

Alternatively, you can create an Intl object in a line of code and run the method:

<code>const valentinesDay = dateFormatter.format( new Date('2022-02-14') );
// 返回美国格式“2/14/2022”

const starwarsDay = dateFormatter.format( new Date('2022-05-04') );
// 返回美国格式“5/4/2022”
</code>
Copy after login
Copy after login

In addition to the format() method, some objects also support the following methods:

  • formatToParts(): Returns an array of objects containing formatted strings, for example { type: 'weekday', value: 'Monday' }
  • resolvedOptions(): Returns a new object containing properties that reflect the locale and formatting options used, such as dateFormatter.resolvedOptions().locale.

Define the locale

All Intl objects require a locale parameter. This is a string that identifies:

  • Language subtag
  • Script subtag (optional)
  • Region (or country) subtag (optional)
  • One or more variant subtags (optional)
  • One or more BCP 47 extension sequences (optional)
  • Special purpose extension sequence (optional)

Language and region are usually sufficient. For example, "en-US", "fr-FR", etc.

In addition to using strings, you can also use the Intl.locale object to construct locales, such as US English in 12-hour format:

<code><label> for="name"></label>{{ NAME }}>
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This can be used in another Intl constructor. For example:

<code>if (window.Intl) {
  // Intl 受支持
}
</code>
Copy after login
Copy after login
Copy after login
Copy after login

If the locale is not defined, the current language and regional settings of the device are used. For example:

<code>const dateFormatter = new Intl.DateTimeFormat('en-US');
</code>
Copy after login
Copy after login
Copy after login
Copy after login

This returns "5/4/2022" on devices set in the United States and "04/05/2022" on devices set in the United Kingdom.

Date and Time

The following tool shows an example of dates and times formatted using Intl.DateTimeFormat() (we are deeply sorry if your language or region is not listed!):

(The CodePen example should be embedded here, but since I can't directly embed external resources, I can only provide a text description.) CodePen example shows multiple ways to format dates and times in different regions and languages ​​using Intl.DateTimeFormat() , including different date styles (full, long, medium, short) and time styles (full, long, medium, short), as well as other options such as calendar, timeZone, etc.

Constructor passes locale and option objects. There are many possible properties for this, although you rarely need to exceed dateStyle and/or timeStyle:

(It should be a table here, but since I can't create the table directly, I can only provide a text description.) The table lists the properties of Intl.DateTimeFormat() and their descriptions, including dateStyle, timeStyle, calendar, dayPeriod >, numberingSystem, localeMatcher, timeZone, hour12, hourCycle, formatMatcher, weekday, era, year, month, day, hour, minute, second, timeZoneName,

,

,

,
<code>const valentinesDay = dateFormatter.format( new Date('2022-02-14') );
// 返回美国格式“2/14/2022”

const starwarsDay = dateFormatter.format( new Date('2022-05-04') );
// 返回美国格式“5/4/2022”
</code>
Copy after login
Copy after login
,

, etc.

Example:

<code>const starwarsDay = new Intl.DateTimeFormat('en-US').format( new Date('2022-05-04') );
</code>
Copy after login

Date range

The formatRange() method takes two dates and formats the period in the most concise way, depending on the locale and options. For example: This method has a smaller browser support range, but it is implemented in Chrome 76.

Relative period

Intl.RelativeTimeFormat() object can display periods relative to this moment. Option object has fewer options:

(It should be a table here, but since I can't create the table directly, I can only provide a text description.) The table lists the properties of Intl.RelativeTimeFormat() and their descriptions, including localeMatcher, numeric, style,

>Wait.

format() method passes values ​​and units: "year", "quarter", "month", "week", "day", "hour", "minute", or "second". Example:
<code><label> for="name"></label>{{ NAME }}>
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Digitals, Currencies, Percentages and Units

The following tool shows an example of formatting numbers, currencies, percentages, and units of measurement using Intl.NumberFormat():

Intl.NumberFormat() (The CodePen example should be embedded here, but since I can't directly embed external resources, I can only provide a text description.) The CodePen example shows how to format numbers, currencies, percentages and units in different regions and languages ​​using notation , including different styles (decimal, currency, percent, unit) and options such as currency, currencyDisplay, unit, unitDisplay, useGrouping, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits,

,

,

, 🎜>,

, Intl.NumberFormat(), numberingSystem, etc. notation styleConstructor passes locale and option objects: currency currencyDisplay (It should be a table here, but since I can't create the table directly, I can only provide a text description.) The table lists the properties of currencySign and their descriptions, including unit, unitDisplay, useGrouping, minimumIntegerDigits >, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits,

,

,

,
<code>if (window.Intl) {
  // Intl 受支持
}
</code>
Copy after login
Copy after login
Copy after login
Copy after login
,

,

,

,

,

,

,

, etc. Intl.ListFormat() typeExample: style

List

The
<code>const dateFormatter = new Intl.DateTimeFormat('en-US');
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Intl.ListFormat() object can format an array of items into a language-sensitive list. In English, this usually requires adding "and" or "or" before the last item.

The following properties can be set in the option object:

(It should be a table here, but since I can't create the table directly, I can only provide a text description.) The table lists the properties of and their descriptions, including , , etc. Example: plural The slightly strange Intl.PluralRules() object supports plural sensitive language rules, where you have multiple items. The option object can set the type property to:
  • Base: the number of things (default value), or
  • Ordinal number: ranking of things, such as first, second or third in English
The

select() method returns an English string representing the plural category of the numeric number (zero, one, two, minority, majority, or other).

Example:

<code><label> for="name"></label>{{ NAME }}>
</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

String comparison

Lastly, the Intl.Collator() object supports language-sensitive string comparisons. Its option object can set the following properties:

(It should be a table here, but since I can't create the table directly, I can only provide a text description.) The table lists the properties of Intl.Collator() and their descriptions, including collation, numeric, etc.

The

compare() method compares two strings. For example:

<code>if (window.Intl) {
  // Intl 受支持
}
</code>
Copy after login
Copy after login
Copy after login
Copy after login

Profit!

If you use JavaScript to display data, you should be able to display information directly in the user's local format. For example, the following code defines a dateFormat() function that uses the Intl short date format or falls back to YYYY-MM-DD if the format is not supported:

<code>const dateFormatter = new Intl.DateTimeFormat('en-US');
</code>
Copy after login
Copy after login
Copy after login
Copy after login

This by itself doesn't make your application easier for international audiences, but it's the first step closer to global distribution.

FAQs (FAQ) about JavaScript Internationalization API (i18n)

What is the purpose of JavaScript Internationalization API (i18n)?

JavaScript Internationalization API (also known as i18n) is a built-in JavaScript API that provides language-sensitive string comparisons, numeric formatting, and date and time formatting. It allows developers to internationalize their applications by providing support for different languages ​​and cultural conventions. This is especially useful for applications used worldwide, as it allows them to adapt to language and format conventions in different regions.

How does JavaScript i18n handle date and time formatting?

JavaScript i18n provides a DateTimeFormat object that can be used to format dates and times according to different cultural conventions. This object takes locale and option objects as parameters, which define the format convention to use. The Options object can specify the format of date, time, time zone, and other aspects of date and time format.

How to deal with digital formatting in JavaScript i18n?

JavaScript i18n provides a NumberFormat object that can be used to format numbers according to different cultural conventions. This object takes locale and option objects as parameters, which define the format convention to use. The option object can specify the style of a number (decimal, percentage, or currency), the use of group separators, the minimum and maximum decimal places, and other aspects of the numeric format.

How to handle string comparisons in JavaScript i18n?

JavaScript i18n provides a Collator object that can be used to compare strings according to different cultural conventions. This object takes locale and option objects as parameters, which define the comparison convention to use. The option object can specify the sensitivity of comparisons (basic, accent, case, or variant), the use of numeric sorting, and other aspects of string comparison.

How to specify locale for JavaScript i18n?

When creating a DateTimeFormat, NumberFormat, or Collator object, you can specify the locale as a parameter. A locale is a string that represents the language and region, such as "en-US" in American English or "fr-FR" in French used in France. If the locale is not specified, the default locale for the JavaScript environment is used.

Can I use multiple locales with JavaScript i18n?

Yes, when creating a DateTimeFormat, NumberFormat, or Collator object, you can specify multiple locales as an array. JavaScript i18n will use the first locale it supports in the array. This is very useful for applications used in multiple regions, as it allows them to adapt to language and format conventions in different regions.

How to customize the formatting options of JavaScript i18n?

When creating a DateTimeFormat, NumberFormat, or Collator object, you can customize the formatting options for JavaScript i18n by providing an option object. The option object can specify aspects of formatting or comparison, such as the format of dates or numbers, the sensitivity of string comparisons, and so on.

Can I use JavaScript i18n with other JavaScript APIs?

Yes, JavaScript i18n can be used in conjunction with other JavaScript APIs. For example, you can use a Date object with a DateTimeFormat object to format dates, or you can use a Number object with a NumberFormat object to format numbers. This allows you to take advantage of the power of JavaScript to internationalize your applications.

Does JavaScript i18n be supported by all browsers?

Most modern browsers (including Chrome, Firefox, Safari, and Edge) support JavaScript i18n. However, it may not be supported by older browsers or some mobile browsers. You can view the compatibility table on the Mozilla Developer Network (MDN) for the latest information on browser support.

Where can I learn more about JavaScript i18n?

You can learn more about JavaScript i18n from the official ECMAScript International API specification, the Mozilla Developer Network (MDN), and various online tutorials and articles. These resources provide detailed information about the API and its usage, as well as examples and best practices for internationalizing JavaScript applications.

The above is the detailed content of What is the JavaScript Internationalization API (I18n)?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template