Thursday, December 31, 2015

How to convert string to variable name in Javascript

If you need to create a variable dynamically on the server side and retrieve the value on the client side, use the next example to use the value assigned:

// Declare the variable name
var myStringName = "echoHello";

// Assign a value to the dynamic string variable
window[myStringName] = "Hello from dynamic string variable!";

// Show value
alert(window[myStringName]);

// Or call the variable name
alert(echoHello);


You can even assign a function to the dynamic string variable:

// Declare the variable name
var myStringName = "alertStringVariable";

// Assign a function to the dynamic variable
window[myStringName] = function () {
    alert("Hello from dynamic function variable...");
}

// Execute the function assigned of the variable
alertStringVariable();