Skip to main content

JavaScript Internationalization

In today's global digital landscape, creating applications that can adapt to different languages, regions, and cultural conventions is crucial. JavaScript's Internationalization API (often called Intl) provides powerful tools to handle these challenges without having to write complex formatting code yourself.

What is Internationalization?

Internationalization (often abbreviated as "i18n" - there are 18 letters between the 'i' and 'n') is the process of designing applications to support various languages and regions. This includes:

  • Displaying dates in the correct format for different regions
  • Formatting numbers, currencies, and percentages appropriately
  • Sorting strings according to language-specific rules
  • Handling plurals and other language-specific grammar rules

JavaScript's built-in Intl object provides standardized, locale-aware functionality for these common tasks.

Getting Started with the Intl Object

The Intl object is the namespace for the ECMAScript Internationalization API. It provides several constructors that let you format dates, numbers, and strings according to locale conventions.

Checking Browser Support

Most modern browsers support the Intl object, but it's always good to check:

javascript
if (window.Intl) {
// Internationalization is supported
console.log("Internationalization API is supported");
} else {
console.log("Internationalization API is not supported");
}

Formatting Dates and Times

One of the most common internationalization needs is properly formatting dates for different regions.

Basic Date Formatting

javascript
// Create a date
const date = new Date('2023-09-15T13:45:30');

// Format the date according to the US locale
const usDateFormatter = new Intl.DateTimeFormat('en-US');
console.log(usDateFormatter.format(date)); // Output: 9/15/2023

// Format the date according to the German locale
const germanDateFormatter = new Intl.DateTimeFormat('de-DE');
console.log(germanDateFormatter.format(date)); // Output: 15.9.2023

// Format the date according to the Japanese locale
const japaneseDateFormatter = new Intl.DateTimeFormat('ja-JP');
console.log(japaneseDateFormatter.format(date)); // Output: 2023/9/15

Advanced Date Formatting

You can also specify how you want the date and time components to be displayed:

javascript
// Format with time
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
};

// UK English uses 24-hour time by default
const ukFormatter = new Intl.DateTimeFormat('en-GB', options);
console.log(ukFormatter.format(date)); // Output: 15 September 2023, 13:45

// US English uses 12-hour time by default
const usFormatter = new Intl.DateTimeFormat('en-US', options);
console.log(usFormatter.format(date)); // Output: September 15, 2023, 1:45 PM

Formatting Numbers

Different regions have different conventions for formatting numbers, such as the thousands separator and decimal point.

Basic Number Formatting

javascript
const number = 1234567.89;

// US English uses commas as thousands separators and period as decimal separator
console.log(new Intl.NumberFormat('en-US').format(number)); // Output: 1,234,567.89

// German uses period as thousands separator and comma as decimal separator
console.log(new Intl.NumberFormat('de-DE').format(number)); // Output: 1.234.567,89

// Indian numbering system groups by thousands, then lakhs (100,000), then crores (10,000,000)
console.log(new Intl.NumberFormat('en-IN').format(number)); // Output: 12,34,567.89

Currency Formatting

javascript
const price = 99.99;

// Format as USD
console.log(new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(price)); // Output: $99.99

// Format as EUR
console.log(new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
}).format(price)); // Output: 99,99 €

// Format as JPY (Japanese yen doesn't use decimal places)
console.log(new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency: 'JPY'
}).format(price)); // Output: ¥100

Percent Formatting

javascript
const percentage = 0.2568;

// Format as percentage
console.log(new Intl.NumberFormat('en-US', {
style: 'percent'
}).format(percentage)); // Output: 26%

// Format as percentage with 2 decimal places
console.log(new Intl.NumberFormat('en-US', {
style: 'percent',
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(percentage)); // Output: 25.68%

String Comparison and Sorting

Different languages have different rules for sorting strings. For example, in Spanish, "ñ" comes after "n" but before "o".

javascript
const strings = ['único', 'naranja', 'ñu', 'manzana'];

// Sort using default JavaScript sorting (uses Unicode code points)
console.log([...strings].sort());
// Output: ["manzana", "naranja", "único", "ñu"] (incorrect for Spanish)

// Sort using Spanish locale
console.log([...strings].sort(new Intl.Collator('es').compare));
// Output: ["manzana", "naranja", "ñu", "único"] (correct for Spanish)

Case-Insensitive Sorting

javascript
const mixedCaseWords = ['Apple', 'banana', 'Cherry', 'date'];

// Sort case-insensitive
const caseInsensitiveCollator = new Intl.Collator('en', { sensitivity: 'base' });
console.log([...mixedCaseWords].sort(caseInsensitiveCollator.compare));
// Output: ["Apple", "banana", "Cherry", "date"]

Pluralization with Intl.PluralRules

Different languages have different plural forms. English has only two forms (singular and plural), but other languages may have more complex rules.

javascript
// Create a plural rules instance for English
const pluralRules = new Intl.PluralRules('en-US');

// Get the plural category for a number
function getPluralMessage(count) {
const category = pluralRules.select(count);

const messages = {
one: `You have ${count} message.`,
other: `You have ${count} messages.`
};

return messages[category];
}

console.log(getPluralMessage(1)); // Output: You have 1 message.
console.log(getPluralMessage(2)); // Output: You have 2 messages.

Relative Time Formatting

The Intl.RelativeTimeFormat API is useful for expressing relative times like "3 days ago" or "in 5 minutes" in different languages.

javascript
// Create a relative time formatter for English
const rtf = new Intl.RelativeTimeFormat('en', { style: 'long' });

console.log(rtf.format(-1, 'day')); // Output: 1 day ago
console.log(rtf.format(2, 'day')); // Output: in 2 days
console.log(rtf.format(-5, 'minute')); // Output: 5 minutes ago
console.log(rtf.format(6, 'month')); // Output: in 6 months

Real-World Example: Multilingual Web App

Here's a practical example of how to implement internationalization in a web application:

javascript
// Function to update UI based on selected locale
function updateUI(locale = 'en-US') {
const now = new Date();
const price = 49.99;
const lastVisit = new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000); // 3 days ago

// Format elements according to locale
document.getElementById('current-date').textContent =
new Intl.DateTimeFormat(locale).format(now);

document.getElementById('product-price').textContent =
new Intl.NumberFormat(locale, {
style: 'currency',
currency: locale.includes('US') ? 'USD' : 'EUR'
}).format(price);

// Calculate days since last visit
const dayDiff = Math.round((now - lastVisit) / (1000 * 60 * 60 * 24));
document.getElementById('last-visit').textContent =
new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(-dayDiff, 'day');
}

// Example usage
document.getElementById('language-select').addEventListener('change', function() {
updateUI(this.value);
});

// Initialize with default locale
updateUI();

In this example, when the user selects a different language from a dropdown, the UI updates to display dates, prices, and relative times according to the selected locale.

Summary

JavaScript's Internationalization API provides powerful tools for creating applications that work seamlessly across different languages and regions. By using the Intl object and its various constructors, you can:

  • Format dates and times according to local conventions
  • Display numbers, currencies, and percentages appropriately
  • Sort strings using language-specific rules
  • Handle plural forms correctly
  • Express relative times in a natural way

These features help make your applications more user-friendly and accessible to a global audience, without having to implement complex formatting logic yourself.

Additional Resources

Exercises

  1. Create a webpage that displays the current date and time in three different locales of your choice.
  2. Build a simple currency converter that formats the output according to the target currency's locale.
  3. Create a blog post interface that shows "Posted X time ago" in different languages using Intl.RelativeTimeFormat.
  4. Build a multilingual contact form that validates and formats phone numbers according to different country formats.
  5. Create a sortable table of names that sorts correctly in multiple languages.

Happy internationalizing your JavaScript applications!



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)