We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 89 – JavaScript Internationalization (Intl API)

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and date and time formatting.

Why Use Intl?

JavaScript's Intl API helps developers create applications that support multiple languages and regions, handling formatting of:

  • Dates and times
  • Numbers and currencies
  • Strings (for comparison and sorting)

Number Formatting

const number = 1234567.89;

// Format as currency
const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});
console.log(currencyFormatter.format(number)); // $1,234,567.89

// Format as decimal in a different locale
const germanNumber = new Intl.NumberFormat('de-DE').format(number);
console.log(germanNumber); // 1.234.567,89

Date and Time Formatting

const date = new Date();

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
  dateStyle: 'full',
  timeStyle: 'short',
});
console.log(dateFormatter.format(date)); // e.g., "Friday, 19 April 2025 at 10:00"

Collator for String Comparison

const words = ['résumé', 'resume', 're?sume?']; // visually similar words

const collator = new Intl.Collator('en', { sensitivity: 'base' });
words.sort(collator.compare);
console.log(words); // Properly sorted based on locale rules

Try Your Hand

  1. Format a number as Japanese Yen (JPY).
  2. Format today’s date in French format with full date style.
  3. Sort an array of names with accents: ["Émile", "Amélie", "Zoé", "Luc"] using Intl.Collator.

Summary

Internationalization is key for building truly global applications!

  • Use Intl.NumberFormat for localized number and currency formatting.
  • Use Intl.DateTimeFormat to display dates and times correctly for a locale.
  • Use Intl.Collator for locale-aware string comparison.