The Intl object for handling internationalization in JavaScript applications

September 16, 2024 6:35 PM

JavaScript Intl

The Intl object is a part of the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and date and time formatting. It is used to help developers create applications that can be easily localized for different languages and regions.


Here are some common uses of the Intl object:


Date and Time Formatting:


const date = new Date();

const formatter = new Intl.DateTimeFormat('en-US', {

  year: 'numeric',

  month: 'long',

  day: 'numeric',

});

console.log(formatter.format(date)); // Output: "September 28, 2023"


Number Formatting:


const number = 1234567.89;

const formatter = new Intl.NumberFormat('en-US', {

  style: 'currency',

  currency: 'USD',

});

console.log(formatter.format(number)); // Output: "$1,234,567.89"


String Comparison:


const collator = new Intl.Collator('en', { sensitivity: 'base' });

console.log(collator.compare('a', 'A')); // Output: 0 (indicating equality)


Plural Rules:

const pluralRules = new Intl.PluralRules('en-US');

console.log(pluralRules.select(1)); // Output: "one"

console.log(pluralRules.select(2)); // Output: "other"


Relative Time Formatting:


const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

console.log(rtf.format(-1, 'day')); // Output: "yesterday"

console.log(rtf.format(1, 'day')); // Output: "tomorrow"


The Intl object provides a powerful set of tools for handling internationalization in JavaScript applications, making it easier to format dates, numbers, and strings according to the conventions of different locales.

Comments


    Read next