3

Does anyone know how could I select a variable from a String in JavaScript? Here's what I'm basically trying to achieve:

var myLang = "ESP";

var myText_ESP = "Hola a todos!";
var myText_ENG = "Hello everybody!";

console.log(myText_ + myLang); // This should trace "Hola a todos!"

Thanks!

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 2
    Relevant: [jQuery Language Switcher](http://stackoverflow.com/questions/13427723/jquery-language-switcher). – Sampson Dec 14 '12 at 16:09

5 Answers5

6
var hellos = {
    ESP: 'Hola a todos!',
    ENG: 'Hello everybody!'
};

var myLang = 'ESP';

console.log(hellos[myLang]);

I don't like putting everything in global scope, and then string accessing window properties; so here is another way to do it.

Chad
  • 19,219
  • 4
  • 50
  • 73
4

If your variable is defined in the global context, you may do this :

console.log(window['myText_' + myLang]); 
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1
var myLang = "ESP";

var myText = {
    ESP : "Hola a todos!",
    ENG : "Hello everybody!"
}

console.log(myText[myLang]); // This should trace "Hola a todos!"
Richard Marr
  • 3,044
  • 1
  • 22
  • 31
1

You can use eval for that but this is very bad practice:

console.log(eval("myText_" + myLang);

I'll suggest to have an object instead:

var myLang = "ESP";
var texts = {
    'ESP': "Hola a todos!",
    'ENG': "Hello everyboy!"
};
console.log( texts[ myLang ] );
antyrat
  • 27,479
  • 9
  • 75
  • 76
0

It is not a good pratice, but you can try using eval() function.

var myLang = "ESP";

var myText_ESP = "Hola a todos!";
var myText_ENG = "Hello everyboy!";

console.log(eval('myText_' + myLang));
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194