Localization in JavaScript
I’m astonished that, even now, there is no standard way to localize JavaScript applications. The existing solutions are either too complex or difficult to use, especially since JavaScript received string interpolation in ES6. It’s plain to see that the obvious approach is:
console.log(T`Hello, World!`);
where T
is a function that takes a string and returns the localized version of it.
With the translation dictionary like this:
const translation = {
'en': {
// 'Hellow, World': 'Hello, World!', we do not need it in English(default locale)
[Some.Enum]: '1st.',
...
},
'ru': {
'Hellow, World': 'Привет, Мир!',
[GrammarPerson.FIRST]: '1-й',
},
'sr': {
'Hellow, World': 'Здраво, Свете!',
[GrammarPerson.FIRST]: '1.',
},
};
export default translation;
The T
function can be implemented like this:
const T = (string) => {
const locale = 'ru'; // get it from the user's preferences
return translation[locale][string] || string;
};
In my Serbian Grammar Trainer (React), I used a bit complex code that allows nested templates and string interpolation, but the idea is the same:
const l10n = (strings: TemplateStringsArray, ...values: string[]): string => {
const r = strings.reduce((prevString: string, nextString: string, index: number) => prevString + (index > 0 ? values[index - 1] : '') + nextString, '');
return translate(r);
};
export default l10n;