How to Create an Internationalisation System Using JavaScript

Ciprian on Wednesday, April 11, 2018 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Creating an i18n system in JavaScript can be tricky. The most popular option is to use global variables (the way WordPress does it using wp_localize_script()), but it is not best practice to fill the global document object with so many variables.

The second choice, and arguably the best one, is to use an array of translatable strings and use on-demand translation.

First, you need to generate an HTML element, in our case, a hidden <span>:

<span id="i18n" data-key-one="My first string" data-key-two="My second string" data-key-three="My third string"></span>

The element can be generated using various methods, such as a PHP loop from a MySQL database, and it should be placed before the closing </body> tag.

Use this JavaScript function for string translation:

/**
* Convert string to camelCase
*
* @param  string string String to convert
*
* @return string        string
*/
function camelCase(string) {
    return string.toLowerCase().replace(/(\-[a-zA-Z])/g, function($1) {
        return $1.toUpperCase().replace('-', '');
    });
}

/**
* Translate string from element
*
* @param  dataAttribute string Data attribute to look for
*
* @return string        string
*
* Usage
*
* Let's assume we have an HTML element like:
* <div id="i18n" data-my-key="String to translate">
*
* We use the function below to translate the string using the data string key:
* translate('my-key');
*/
function translate(dataAttribute) {
    let element = document.querySelector('#i18n'),
        dataAttributeCamelCase = camelCase(dataAttribute),
        string = element.dataset.[dataAttributeCamelCase];

    string = (string.length) ? string : '';

    return string.toString();
}

Use the translation function in your JavaScript code as below:

<div id="my-id">This should be translated and replaced with <code>key2</code> variable.</div>

<script>document.querySelector('#my-id').innerHTML = translate('key-two');</script>

See a demo here.

Fun fact: I18n is a numeronym – 18 stands for the number of letters between the first i and last n in internationalization, a usage coined at DEC in the 1970s or 80s.

Related posts

Leave a Reply

You have to agree to the comment policy.