Convert String to JavaScript Variable / Method
eval() is JavaScript methods to use convert the string to variable, this will help in many situation, in the following situation we can use this.Case 1
Some time the variable is stored into value, in this situation we can convert it to variable.Example
1
var test="count";
var count=100;
alert(eval(test)); //100
2
var arr=["var1","var2","var3","var4","var5"];
var var1="Value1";
var var2="Value2";
var var3="Value3";
var var4="Value4";
var var5="Value5";
for(i=0;i<arr.length;i++)
{
alert(eval(arr[i]));
}
Output:
Value1
Value2
Value3
Value4
Value5
Case 2
If we want to use the replace JavaScript method like below you should need the eval() help.Example
var chr="a";
alert( ("abababab").replace(/chr/g,"L") );
Output:
abababab
In the above situation chr will consider as string, but in there we need to assign variable. So we can use the eval() like below example.
var chr="a";
alert( eval("('abababab').replace(/"+chr+"/g,'L')") );
Output:
LbLbLbLb
Example Program:- (Editor)
Editor is Loading...
Advertisement
0 comments:
Post a Comment