Is there a way to refer to a Javascript variable with a string that contains its name?
example:
var myText = 'hello world!'; var someString = 'myText'; //how to output myText value using someString?
Place the character f before you start a string literal with single/double quotes as shown below. Now, we can reference variables inside this string. All we need to do is enclose the variables with curly braces {variable} and place this variable inside the string value, wherever required.
A string variable is identified with a variable name that ends with the $ character. A string array variable has the $ character just before the left bracket that holds the array index. The variable name must begin with a letter and consist of 30 or fewer characters, including the $ character.
A string is a type of value that can be stored in a variable.
You can use an eval
to do it, though I try to avoid that sort of thing at all costs.
alert(eval(someString));
A better way, if you find yourself needing to do this, is to use a hash table.
var stuff = { myText: 'hello world!' }; var someString = 'myText'; alert( stuff[someString] );
If that variable is on the global scope, you can use the bracket notation on the global object:
var myText = 'hello world!'; var someString = 'myText'; alert(window[someString]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With