Convert string to variable name in JavaScript

ID : 10281

viewed : 30

Tags : javascriptvariablesjavascript

Top 5 Answer for Convert string to variable name in JavaScript

vote vote


If it's a global variable then window[variableName] or in your case window["onlyVideo"] should do the trick.

vote vote


Javascript has an eval() function for such occasions:

function (varString) {   var myVar = eval(varString);   // ..... } 

Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need

function SetTo5(varString) {   var newValue = 5;   eval(varString + " = " + newValue); } 

or if using a string:

function SetToString(varString) {   var newValue = "string";   eval(varString + " = " + "'" + newValue + "'"); } 

But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()

vote vote


As far as eval vs. global variable solutions...

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

var tempNamespace = {}; var myString = "myVarProperty";  tempNamespace[myString] = 5; 

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

vote vote


var myString = "echoHello";  window[myString] = function() {     alert("Hello!"); }  echoHello(); 

Say no to the evil eval. Example here:

vote vote


You can access the window object as an associative array and set it that way

window["onlyVideo"] = "TEST"; document.write(onlyVideo); 

Top 3 video Explaining Convert string to variable name in JavaScript