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.
Intl.DateTimeFormat()
and Intl.NumberFormat()
, which accept locale identifiers to present information in a format familiar to the user. Intl.RelativeTimeFormat
) and plural sensitive formatting (Intl.PluralRules
) allow for more nuanced and culturally compliant applications. 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:
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>
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:
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.
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:
(Please note that date separator slashes are not commonly used in all languages!)
The number "1,000" will be interpreted as:
Even in English alone, the situation can be complicated. The term “1,000 meters” means:
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>
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>
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>
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>
In addition to the format() method, some objects also support the following methods:
All Intl objects require a locale parameter. This is a string that identifies:
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>
This can be used in another Intl constructor. For example:
<code>if (window.Intl) { // Intl 受支持 } </code>
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>
This returns "5/4/2022" on devices set in the United States and "04/05/2022" on devices set in the United Kingdom.
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>
Example:
<code>const starwarsDay = new Intl.DateTimeFormat('en-US').format( new Date('2022-05-04') ); </code>
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.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
,
format() method passes values and units: "year", "quarter", "month", "week", "day", "hour", "minute", or "second". Example:
<code><label> for="name"></label>{{ NAME }}> </code>
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
style
Constructor 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>
,
,,
,, etc. Intl.ListFormat()
type
Example: style
List
The<code>const dateFormatter = new Intl.DateTimeFormat('en-US'); </code>
(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:
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>
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.
compare() method compares two strings. For example:
<code>if (window.Intl) { // Intl 受支持 } </code>
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>
This by itself doesn't make your application easier for international audiences, but it's the first step closer to global distribution.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!