Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to variable name in JavaScript

I’ve looked for solutions, but couldn’t find any that work.

I have a variable called onlyVideo.

"onlyVideo" the string gets passed into a function. I want to set the variable onlyVideo inside the function as something. How can I do that?

(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if statements.)

Edit: There’s probably a better way of doing what you’re attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.

A simple intro:

// create JavaScript object var obj = { "key1": 1 };  // assign - set "key2" to 2 obj.key2 = 2;  // read values obj.key1 === 1; obj.key2 === 2;  // read values with a string, same result as above // but works with special characters and spaces // and of course variables obj["key1"] === 1; obj["key2"] === 2;  // read with a variable var key1Str = "key1"; obj[key1Str] === 1; 
like image 754
switz Avatar asked Apr 10 '11 18:04

switz


People also ask

How do you name a variable in JavaScript?

Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.

How do you turn a variable into a string in JavaScript?

The String() method converts a value to a string.

What is meant by ${} in JavaScript?

In Javascript the ${} is used to insert a variable to a string. var foo = "cheese"; console.


1 Answers

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

like image 55
ingo Avatar answered Oct 16 '22 00:10

ingo