How to Create an Internationalisation System Using JavaScript

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

👋 Added by Ciprian on Wednesday, April 11, 2018 in Blog, JavaScript. Last modified on Thursday, May 24, 2018.


Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy