Categories
Android Update Internet Latest news Technology Reviews

javascript: Formatting Lists of Items With the Intl Javascript API

Matías Hernández: [0:00] Another use case for the Intl object is to format a list, or a set, or collections of items. In different languages, lists of items can be sorted, spaced, even connected differently. If you want to support different languages, you need to support this use case using the Intl.listFormat constructor.
[0:22] Let’s try to use the constructor. Create a function to get the formatter and pass the correct locale default, ‘en-US’. Then, let’s create two variables with different formatters for different locales, in this case for English and Chinese. Let’s console.log the result of these, passing just one item. Both look the same.

[0:46] What happen if you have multiple items inside the argument of the format method? Let’s check it out. Let’s create a bigger list and let’s pass different number of items, [‘one’, ‘two’, ‘three’] , [‘one’, ‘two’, ‘three’, ‘four’]. Let’s do the same with the other formatter, in this case, Chinese, just change the variable name here.

[1:15] Save and let’s see how this works. For English, you know the drill, one, one and two, one, two, and three. In English, the items are separated by spaces and connected with commas, and with the “and” word.

[1:33] What happened in other languages? Let’s see the Chinese example. You can notice that it’s not actually split by spaces and the commas are in the opposite side. Using the listFormat constructor from the Intl object, you can handle different ways of representing lists of string items in different languages.