Working With Intl

Internationalization - something you constantly hear developers talking about but rarely actually see people using in practice - is getting a kick in the pants with the new ECMAScript Internationalization API. Currently supported in Chrome 24, Chrome for Android, Firefox 29, IE 11, and Opera 15 (sadly no Safari support), the new Intl namespace provides a set of functionality to add internationalization to your numbers, dates, and sorting. In this article I'll demonstrate the major features of Intl and get you on the path to adopting support for the billions of people on the Internet who live outside your own country!

Core Features

The Intl namespace covers three main areas of functionality:

  • Formatting numbers
  • Formatting dates
  • Sorting strings

Within each of these are various options for controlling both the locales used for formatting as well as formatting options. As an example, the number formatter includes support for handling currency. The date formatter has options for what parts of the date to display.

Lets take a look at a few examples.

Our Application

Our first application is a simple data reporter. It uses AJAX to fetch a set of data containing dates and numbers. First, the HTML:

Listing 1: test1.html:

Make note of the empty table. That's where we will be dumping our data. Now let's take a look at the JavaScript.

Listing 2: app1.js:

All that the code does here, is make an AJAX call to a file and render the result to the data. The data file, stats.json, is simply an array of ten hard coded values. Here is a portion of the file:

As you can see, the dates are formatted as month/date/year and the numbers are passed, as is. This renders acceptably:

But note the the numbers are a bit hard to read without formatting. Let's begin by adding some formatting to the numbers.

Adding Number Formatting

The following modifications can be seen in app2.js and tested with test2.html. First, I'll modify my code to call a new function, numberFormat:

And here is that function:

The function begins by checking if Intl exists as part of the window object. If it does, we then check to see if we've made the formatter before. The Intl object creates a formatting object that you can reuse, and since we're formatting a bunch of numbers, we only want to create it one time. Which is exactly what we do as soon as we see that we need too. We don't bother with any options for now, just to keep it simple. Finally, if there was no support for Intl at all, we just return the number as is. The result is a significant improvement, with minimal work:

Cool! So, how do we test other languages? You may be tempted to check your browser settings. All browsers have a preference for language, but unfortunately, changing the language in the browser is not enough. Changing it does impact how the browser behaves. 

If you open your dev tools and look at network requests, you can see that a header called "Accept-Lanage" will change based on your settings. If you add French, for example (I'm assuming you aren't a native French speaker), you will see "fr" added to this header. But this does not impact Intl. Instead, you have to change your operating system language and restart the browser. This is not as scary as it sounds. When I tested, I was worried my entire operating system would change immediately. But in my tests, I was able to change the language, restart my browser, and see the change. I quickly changed back. The Intl formatter functions allow you to override the current locale and pass one in instead.

I modified the application to allow the end user to specify a language via a drop down. Here's the modification made to the HTML. (This modification may be found in test3.html)

The languages I picked were pretty arbitrary. Next - I updated my application code to listen to changes to this drop down as well as checking the desired locale when formatting.

Listing 3: app3.js:

Starting at the bottom - note that I've added a simple event handler for changes to the drop down. When a change is detect, the table is emptied out and the function getStats is run. This new function simply abstracts the AJAX code used previously. The real change now is in numberFormat. I check the language selected and if one of them was chosen, we pass that as the locale to the NumberFormat constructor. Note that if something wasn't chosen, we default to navigator.language. This now gives us a way to quickly test different locales and see how they render numbers.

Adding Date Formatting

Now is a perfect time to take care of the other column of data - the numbers. I followed the same style as before and added a call to a new function, dateFormat.

And here is dateFormat (You can find the code in app4.js, which is used by test4.html):

This is very similar to number formatting, except this time we are explicitly passing some options when we create the formatter. The options specify both what fields are visible in the date, as well as how they look. Each part of a date can be shown or not, and each one has different options. The options include:

  • weekday
  • era
  • year
  • month
  • day
  • hour
  • minute
  • second
  • timeZoneName

For a full list of what values you can use, see the MDN documentation for DateTimeFormat, but as an example, months can be displayed as a number or in different textual forms. So what does this create? Here is the English version:

And here it is in French:

You may be wondering - what covers the location of each field? As far as I can tell, you have no control over this. You could, of course, create multiple formatters and then combine them together, but using one formatter the layout of the fields is driven by internal logic. If you turn off the day of the month, for example, here is what you get: April 2013 Monday. Why? Honestly I have no idea.

Finally - note that you need to pass a date value, not a string, to the formatter. You can see where I use the date constructor in the formatter to parse my string-based date. This is - a bit loose - so keep this in mind when using this functionality.

Show Me the Money

Currency formatting isn't a separate object, but rather an optional use of the number formatter. For the next demo, we've created a new data file, stats2.json, and added a "sales" column to our data. Here is a sample:

The column was added to the HTML (test5.html), added within the JavaScript iterating over the rows of data (see app5.js), and passed to a new function called currencyFormat. Let's look at that.

Displaying numbers as currencies requires two optional values. First, a style of "currency", and then the currency type. Other options (like how to display the name of the currency) exists as well. Here comes the part that may trip you up a bit. You must specify the currency type. 

You may think - how in the heck do I figure out the currency type for all the possible values? The possible values are based on a spec (http://www.currency-iso.org/en/home/tables/table-a1.html) and in theory you could parse their XML, but you don't want to do that. The reason why is pretty obvious but I can honestly say I forgot initially as well. You do not want to just redisplay a particular number in a locale specific currency. Why? Because ten dollars American is certainly not the same as ten dollars in pesos. That's pretty obvious and hopefully I'm the only person to forget that.

Using the code above, we can see the following results in the French locale. Note how the numbers are formatted right for the locale and the currency symbol is placed after the number.

Sorting With Collator

For our final example, we'll look at the Collator constructor. Collators allow you to handle text sorting. While some languages follow a simple A to Z ordering system other languages have different rules. And of course, things get even more interesting when you start adding accents. Can you say, for certain, if ä comes after a? I know I can't. The collator constructor takes a number of arguments to help it specify exactly how it should sort, but the default will probably work well for you.

For this example, we've built an entirely new demo, but one similar to the previous examples. In test6.html, you can see a new table, for Students. Our new code will load up a JSON packet of students and then sort them on the client. The JSON data is simply an array of names so I'll skip showing an excerpt. Let's look at the application logic.

Listing 4: app6.js:

As I said, this code is pretty similar to the previous examples, so focus on getStudents first. The crucial line here is: s.sort(sorter). We're using the built in function for arrays to do sorting via a custom function. That function will be passed two things to compare and must return -1, 0, or 1 to represent how the two items should be sorted. Now let's look at sorter.

If we have an Intl object, we create a new Collator (and again, we're allowing you to pass in a locale) and then we run the compare function. That's it. As I said, there are options to modify how things are sorted, but we can use the defaults. The fallback is localeCompare, which will also attempt to use locale specific formatting, but has (in this form) slightly better support. We could check for that support as well and add one more fallback for really good support, but I'll leave that for you, as an exercise.

We've also modified the front end to use Swedish as a language. I did this because the excellent MDN documentation showed that it was a good way to see the sorting in action. Here's the English sort of our student names:

And here it is in Swedish:

Note how ätest is sorted differently. (Sorry, I couldn't think of a name that began with ä.)

Wrap Up

All in all, the Intl class provides some very simple ways to add locale specific formatting to your code. This is certainly something you can find now, probably in a few thousand different JavaScript libraries, but it is great to see the browser manufacturers adding in support directly within the language itself. The lack of iOS support is a bummer, but hopefully it will be added soon.

Thanks goes to the excellent Mozilla Developer Network for its great Intl documentation.

Tags:

Comments

Related Articles