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!

1

5 Answers 5

5
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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

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

1 Comment

Thanks man, you just saved my life and that of my neurons! :)
1
var myLang = "ESP";

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

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

Comments

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

Comments

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

2 Comments

eval() is really powerful, but it's worth noting that its power can be abused. It can be a security (and code maintenance) liability.
Thank for the commend Richard. THis is the reason why I said it is not a good pratice. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.