Guide to Internationalization in JavaScript

What Is Internationalization in JavaScript?

Internationalization, also called i18n, involves creating a new website or changing your current site in such a way that your site can adapt to a certain local language. Localization, which we touched on in the introduction, is the next step that developers can take to implement one or more languages.

Internationalizing sites is easier these days with the many open-source JavaScript libraries available. I’ve found the following libraries to be quite useful.

FormatJS

FormatJS is a collection of JavaScript libraries that helps with number, time, and date formatting. Not only that, but this library also helps you compare language-sensitive strings. The best part is that it includes React-Intl, thus making your React JavaScript app development easier.

AngularI18N

If your app is in Angular, AngularI18N will help you with templates and tools. You can use this library to build helpers that can internationalize and localize your app.

Moment.js

Moment.js helps with streamlining the date-time format. It can also match the format in a specific time zone.

i18next

You can use i18next with Vue, Angular, React, or any framework of your choice. The library helps detect the user’s language. Once done, i18next loads and inserts translations. In addition, it also supports standard features of i18n.

Globalize JS

One of the most popular libraries, Globalize JS uses the Common Locale Data Repository (CLDR), the largest available base of locale data. The library uses CLDR to get the formatting and paring pattern for date-time, number, messages, units, and currencies.

In the next section, I’ll guide you on how to internationalize your JavaScript web app using Globalize. We’ll use Globalize because it uses the largest standard database of locale data.

A Guide to Internationalization Using Globalize JS

As I noted in the previous section, Globalize uses CLDR from the Unicode Consortium. Because it has such a huge base, you don’t have to think about adding any additional modules. Besides, you don’t need to use the entire library. The content is separated from the code. So, if you want to use the locale data for, say, two or three specific zones, you can pick the modules that you need.

Let’s get started. We’ll discuss the installation first and then move on to the features.

How to Install

Your first step is to find out what modules you need. Check out this link, which lets you can check or uncheck the modules. The site will tell you what CLDR JavaScript files and JSON files you need and in what order you need to arrange them.

To install Globalize, you need to have Node.js installed in your system. If you already have Node.js, you can install the entire Globalize library along with its dependencies by running the following command in cmd using npm.

npm install globalize cldr-data --save

Now, let’s find out how to format the date-time, language, and currency using Globalize.

Formatting the Date

First, you need to include the library in your code. You can do that as follows:

var Globalize = require('globalize');

Next, include the CLDR data:

var cldrData = require('cldr-data');

And don’t forget to load the supplemental data:

Globalize.load(cldrData.entireSupplemental());

Finally, load the specific locale data that you need. For this example, I’ll show you how to format your date-time in the Italian format.

Globalize.load(cldrData.entireMainFor('it', 'en-US', 'en-GB'));

Now, let’s format the date in the U.S., UK, and Italian formats:

// Here, we declare today's date
var date = new Date(2020, 2, 15);

// Print date in Italian format
console.log(Globalize('it').formatDate(date));

// Print date in US format
console.log(Globalize('en-US').formatDate(date));

// Print date in UK format
console.log(Globalize('en-GB').formatDate(date));

In the console, you’ll get the following outputs:

"15/2/2020"
"02/15/2020"
"15/02/2020"

Now let’s try formatting a number.

Formatting the Number

To format numbers, first you have to add the CLDR data and supplemental data. Then you have to load the locale data. The steps are the same as before. Now, let’s see the code to format the number.

var number = 1452.67;

// Format in IT standard
console.log(Globalize('it').formatNumber(number));

// Format in US standard
console.log(Globalize('en-US').formatNumber(number));

You’ll get the following output:

"1.452,67"
"1,452.67"

Formatting the Currency

Now let’s try something interesting. How about we format a currency?

After adding the required CLDR and local data, let’s declare a number and format it in U.S. dollars (USD) and euros (EUR).

var value = 456.342;
//Currency formatter for USD

var usdollarFormat = enGlobalize.currencyFormatter('USD');

console.log(usdFormatter(value));

//Currency formatter for EURO

var euroFormat = enGlobalize.currencyFormatter('EUR', {
  style: 'code',
  round: 'ceil'
});

console.log(eurFormatter(value));

You’ll get the following output:

$456.34
456.34 EUR

Formatting the Language

We saved the interesting stuff for last. Date-time and number formatting are simple. But you may wonder how to change the text content of your website. Well, Globalize JS helps you with that as well. But for that, you need to manually declare the translated data in a JSON file.

For example, let’s suppose you need to translate your site’s homepage. We can start with the register and cancel buttons. In the it.json file, write

{
  "it":
      { 
        "register": "Registrati",
        "cancel":"Annulla"
      }
}

Write the other texts and their translated versions in the JSON.

Now it’s time to fetch the data from the JSON and pass them in order to globalize:

const fetchHeaders = new Headers({"accept": "application/json", 'X-Requested-With': 'XMLHttpRequest'});
var locale = it;
fetch("messages/" + locale + ".json", { headers: fetchHeaders }).then(response => {
return response.json();
})
   .then(
         json => {
                  Globalize.loadMessages(json);
                  Globalize.locale(locale);
                  yourRender();
                  }
         );

Here, the locale is the variable where you declare the JSON filename. If the region is Italy (IT), the code wants the file to be present at messages/it.json. Similarly, if you have JSON for other countries, such as France (fr.json) or Japan (jp.json), the code will fetch data from the respective JSONs and translate the texts accordingly. For translating, you need the following code:

function translateButtons() {
	//To translate the Register button
    document.getElementById( "buttonRegister" ).value = Globalize.formatMessage( "register" );
	//To translate the Cancel button
    document.getElementById( "buttonCancel" ).value = Globalize.formatMessage( "cancel" );
}

Globalize JS also helps to format pluralization, relative time, units, and many other kinds of stuff. Select the module you like and start internationalizing your site.

Now that the code is ready, you may wonder how you can find the geolocation of the users accessing your site. In the next section, I’ll introduce you to ipdata, an easy-to-use geolocation API.

How ipdata Can Help With Internationalization

ipdata provides you with a geolocation API. Using that, you can find the location of any user with their IP address, both IPv4 and IPv6. Let’s see how you can do that. Run the following JavaScript code:

var request = new XMLHttpRequest();

//The GET call returns the location of the IP address of the request’s origin
request.open('GET', 'https://api.ipdata.co/?api-key=test');
request.setRequestHeader('Accept', 'application/json');
//Function executes when readystate changes
request.onreadystatechange = function () {

  if (this.readyState === 4) {
    console.log(this.responseText);
  }
};
request.send();

You need to ensure one thing—that all calls are made using https. ipdata doesn’t serve requests on unsecured http. You can use the ipdata API not only in JavaScript but also in C#, Java, Python, PHP, and many other languages. Sign up to get a free API key and start testing.

The best feature of ipdata, apart from location, is that you can also use the API to detect the mobile carrier, currency, and time zone, along with proxies and threats.

Expand Your Limits With Internationalization

While developing a website, remember the “world” in WWW. Your site is meant to be accessed by people from around the world. No matter what kind of site you’re developing, be it e-commerce or a travelogue, target your audience. Find out the locale where your site is meant to be a hit. Start using internationalization in JavaScript and make your site readable by people from different countries with different languages.

This post was written by Arnab Roy Chowdhury. Arnab is a UI developer by profession and a blogging enthusiast. He has strong expertise in the latest UI/UX trends, project methodologies, testing, and scripting.