Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 608
Albert Espinosa Aguado Avatar asked Jun 04 '26 18:06

Albert Espinosa Aguado


1 Answers

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.

like image 181
Chad Avatar answered Jun 06 '26 08:06

Chad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!