Lets say, we grabed a function call from somewhere and have it in a variable. Like,
 
var ca='call_me("test","123")';

How can we trigger "call_me" function in the above code? just printing the variable? No. It won't work. Can we use "eval" function? Yes, It does work.
But there is some concerns about using this method as it leads to some serious security flaws and it is hard to debug. Moreover its a depreciated function, so avoid it using in your projects.

However if you still interested in using this method, you can do it like this:
 
eval(ca);

But the best way to do this is to check the "window" object which has all the items related to current window and then call if the function exists. So we can check whether there is any reference to our function in the window object, if yes we can proceed calling like this:

window[function_name](arguments) which transforms into window['call_me']("test","123");

That finishes the topic. But if you have any doubts in splitting the parameters from the variable, you may read below.

How do you grep the function parameters separately from the string? One way of doing that is to use Regular Expression. Yes, grabbing the contents inside brackets and splitting using comma will work. Example, for the above function we can do like this:

1) Match the function name,
   var fn=ca.substr(0,ca.indexOf('('));

2) Then the parameters,
    var parameters=ca.match(/(([^)]+))/)[1];

3) and call the function after splitting the parameters into an array,
   var p1=parameters.split(',');
   window[fn](p1[0],p1[1]);

The whole process looks like this:
<script type='text/javascript'>
function call_me(val,val1){
	alert('the values are '+val+'#'+val1);
}

var ca='call_me(test,123)';
var parameters=ca.match(/(([^)]+))/)[1];
var p1=parameters.split(',');
var fn=ca.substr(0,ca.indexOf('('));
if(typeof(window[fn])=='function')
	window[fn](p1[0],p1[1]);

</script>
Though this isn't the easy way, when you are in a situation to call a javascript function from a string, this is the best & safe way of doing things.






Comments (0)
Leave a Comment

loader Posting your comment...