Get variable from a string

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!

Upvotes: 3

Views: 189

Answers (5)

antyrat
antyrat

Reputation: 27765

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 ] );

Upvotes: 1

Richard Marr
Richard Marr

Reputation: 3064

var myLang = "ESP";

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

console.log(myText[myLang]); // This should trace "Hola a todos!"

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38618

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));

Upvotes: 0

Chad
Chad

Reputation: 19619

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.

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382274

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

console.log(window['myText_' + myLang]); 

Upvotes: 4

Related Questions