Internationalization

Introduction

Welcome to this lesson focusing on the Intl class in JavaScript. This class is a part of the ECMAScript Internationalization API, providing language sensitive string comparison, number formatting, and date and time formatting. The Intl class helps developers handle internationalization, ensuring that web applications can adapt to different languages and regions.

Internationalization, often abbreviated as i18n, is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. JavaScript’s Intl object is a namespace that provides this functionality.

Lesson Objectives

By the end of this lesson, you will be able to:

  1. Understand the purpose and use of the Intl class in JavaScript.
  2. Use Intl to format numbers, dates, and times based on different locales.
  3. Compare strings across different languages and locales.

The Intl Object

The Intl object serves as a namespace for the ECMAScript Internationalization API, meaning it’s not a constructor and doesn’t have any instances. Instead, it contains constructors for several internationalization objects.

1. Intl.DateTimeFormat

The Intl.DateTimeFormat object enables language-sensitive date and time formatting.

Example: Formatting a Date in Norwegian

javascript
	let date = new Date();
	let norwegianDateFormatter = new Intl.DateTimeFormat('no-NO');
	console.log(norwegianDateFormatter.format(date)); // Outputs date in Norwegian format

2. Intl.NumberFormat

Intl.NumberFormat allows for the language-sensitive formatting of numbers.

Example: Formatting Currency in Norwegian Krone

javascript
	let price = 1234.56;
	let norwegianCurrencyFormatter = new Intl.NumberFormat('no-NO', { style: 'currency', currency: 'NOK' });
	console.log(norwegianCurrencyFormatter.format(price)); // Outputs "kr 1 234,56"

3. Intl.Collator

Intl.Collator object enables language-sensitive string comparison.

Example: Norwegian Alphabetical Sorting

javascript
	let words = ['ørret', 'ås', 'elv', 'fjell'];
	let norwegianCollator = new Intl.Collator('no-NO');
	words.sort(norwegianCollator.compare);
	console.log(words); // Outputs sorted array based on Norwegian alphabet

Practical use cases of Intl

Practical Example of Using Intl in a Production Code Base

Scenario: E-commerce Website

Imagine we are developing an e-commerce website that serves customers in multiple countries, including Norway and the United States. Our goal is to display product prices, dates, and sort product names according to the user’s locale.

Objective

The primary objective is to enhance user experience by displaying prices, dates, and sorting product names in a format that’s familiar to the user based on their locale.

Implementation

  1. Locale Detection: First, we detect the user’s locale. This can be achieved through various methods, such as browser settings, user profile preferences, or IP geolocation.

    javascript
    	const userLocale = navigator.language || 'en-US'; // Fallback to 'en-US' if unable to detect
  2. Price Formatting: Use Intl.NumberFormat to format the product prices according to the user’s locale and currency.

    javascript
    	function formatPrice(price, locale, currency) {
    	    const formatter = new Intl.NumberFormat(locale, {
    	        style: 'currency',
    	        currency: currency
    	    });
    	    return formatter.format(price);
    	}
    	
    	// Example Usage
    	const priceInUserLocale = formatPrice(1234.56, userLocale, userLocale === 'no-NO' ? 'NOK' : 'USD');
  3. Date Formatting: Use Intl.DateTimeFormat to format dates. This is particularly useful for displaying order dates, shipping dates, etc.

    javascript
    	function formatDate(date, locale) {
    	    const formatter = new Intl.DateTimeFormat(locale);
    	    return formatter.format(new Date(date));
    	}
    	
    	// Example Usage
    	const orderDate = formatDate('2024-01-28', userLocale);
  4. Product Name Sorting: For an alphabetically sorted product list, use Intl.Collator to sort names based on the user’s language.

    javascript
    	function sortProductNames(names, locale) {
    	    const collator = new Intl.Collator(locale);
    	    return names.sort(collator.compare);
    	}
    	
    	// Example Usage
    	const products = ['ørret', 'ås', 'elv', 'fjell'];
    	const sortedProducts = sortProductNames(products, userLocale);

By integrating the Intl object in these ways, the e-commerce website becomes more accessible and user-friendly for an international audience. The prices, dates, and product listings automatically adapt to the user’s local preferences, enhancing the overall user experience and potentially increasing global engagement and sales.

Conclusion

The Intl class in JavaScript is an incredibly powerful tool for internationalizing web applications. By understanding and utilizing Intl.DateTimeFormat, Intl.NumberFormat, and Intl.Collator, you can ensure that your application is accessible and relevant to users worldwide, regardless of their language and regional preferences.


Lesson Task

Brief

You are developing a feature for a website that displays user reviews. These reviews include the username, country of origin, the review date, and the review text. Your task is to format the review date according to the user’s country of origin.

Requirements:

  1. Create a function formatReviewDate that takes two arguments: the review date (as a string or Date object) and the user’s locale (as a string).
  2. Use Intl.DateTimeFormat to format the date according to the user’s locale.
  3. Test this function by formatting a sample date for at least two different locales (e.g., ‘no-NO’ for Norway and ‘en-US’ for the United States).

Sample Data:

  • Date: ‘2024-01-28’
  • Locales: ‘no-NO’, ‘en-US’

Solution

javascript
	// Function to format a review date based on the user's locale
	function formatReviewDate(date, locale) {
	    // The Intl.DateTimeFormat object is used to format the date
	    // according to the specified locale
	    const formatter = new Intl.DateTimeFormat(locale);
	
	    // The format method applies the locale-specific formatting
	    // to the input date and returns it as a string
	    return formatter.format(new Date(date));
	}
	
	// Testing the function with different locales
	const sampleDate = '2024-01-28';
	console.log(formatReviewDate(sampleDate, 'no-NO')); // Formats the date in Norwegian style
	console.log(formatReviewDate(sampleDate, 'en-US')); // Formats the date in US style

In this code:

  • The formatReviewDate function is defined to take a date and a locale as inputs.
  • Inside the function, Intl.DateTimeFormat is instantiated with the provided locale. This object handles the locale-specific date formatting.
  • The format method is used to apply the formatting to the provided date, which is converted to a Date object if it’s not already one.
  • Finally, the function is tested with a sample date and two different locales, demonstrating how it adapts the date format based on the locale.

Additional resources

MDN Docs: Intl