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
- Format a number as Japanese Yen (JPY).
- Format today’s date in French format with full date style.
- Sort an array of names with accents:
["Émile", "Amélie", "Zoé", "Luc"]
usingIntl.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.