I trying to work with objects and arrays for localization purposes. Now the issue is, that it requires a lot of coding to load the correct value from the objects 1-by-1.
As such, I tried to simplify the process by creating variable names out of other variables. Therefore I check for the lang
-attribute and try to get that value as part of another variable name.
However, this does not work at all.
As example I could have an object var text = { en: 'text', de: 'text' }
I could make load the correct text by using:
var language = document.documentElement.lang.toLowerCase();
switch (language) {
case 'en':
element.innerHTML = text.en;
break;
case 'de'
element.innerHTML = text.de;
break;
}
This will be really annoying to code so I tried to use following methodes instead:
element.innerHTML = text.language;
element.innerHTML = `text.${language}`;
...
None of this works of course.
So I'm really in need of help to find a way to create a variable name by merging different variable names such as:
var a = 'text.';
var b = 'en';
var c = a.b; => text.en;
In the end, it must be recognized as a variable name and not as a string!
var text = {
en: 'Hello World',
de: 'Hallo Welt',
es: 'Hola Mundo',
it: 'Ciao Mundo',
fr: 'Bonjour Le Monde'
}
/* getting the language of the document */
var language = document.documentElement.lang.toLowerCase();
window.addEventListener('DOMContentLoaded', function() {
var ele = document.body;
/*does obviosly not work*/
var content = `text.${language}`;
ele.innerHTML = content;
/*does work*/
console.log(`the set language is: ${language}`);
});
<!DOCTYPE html>
<html lang="de" dir="ltr">
<head></head>
<body></body>
</html>