Recipe 16Creating Language-Sensitive Lists with Intl.ListFormat()

Task

Let’s say you have a gaming app and want to display the top three players of the week based on their scores. Because your app is available in multiple languages, you need a function that can format the list automatically based on the user’s language preference. It’s fairly common to have a series of items like this stored in an array that you need to format as a sentence in different languages.

Solution

Use the Intl.ListFormat() constructor:

1: const​ topPlayers = [​"Kraken"​, ​"Boss99"​, ​"Ninja"​];
const​ msg = ​"Congratulations to this week's winners: "​;
function​ getFormattedList(lang, arr) {
5: const​ formatter = ​new ...

Get Text Processing with JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.