Skip to content

Instantly share code, notes, and snippets.

@hto
Created March 3, 2020 19:39
Show Gist options
  • Save hto/da14993198e348ec7ba61f414d18b133 to your computer and use it in GitHub Desktop.
Save hto/da14993198e348ec7ba61f414d18b133 to your computer and use it in GitHub Desktop.
Javascript simple localization methods
module.exports = {
currentLang: 'en',
textList: null,
setLang: function(lang) {
this.currentLang = lang;
this.textList = require(lang);
},
__t: function(key) {
return typeof this.textList[key] === "undefined" ? "-" : this.textList[key];
},
__s: function(...key) {
return typeof this.textList[key[0]] === "undefined" ? "-" : (this.textList[key[0]]).replace('%s1',key[1]).replace('%s2', key[2]);
}
}
@hto
Copy link
Author

hto commented Mar 3, 2020

language files that should be in the same directory

en.js

module.exports = {
    "HELLO": "hello", // S:15 C:23
    "HELLO": "helloo", // S:25 C:23
    "WORLD": "word",
    "PAGINATION": "Pages: %s1 of %s2"
}

tr.js

module.exports = {
    "HELLO": "merhaba",
    "WORLD": "muz",
    "PAGINATION": "Sayfalar: %s1 - %s2"
}

use

const loc = require('./localization.js');
loc.__t('HELLO');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment