I have a string that is my javaScript function:
var foo = "CONCATENATE('a', ' ', 'b')";
How to make javaScript call of this function without using eval()
?
I have a string that is my javaScript function:
var foo = "CONCATENATE('a', ' ', 'b')";
How to make javaScript call of this function without using eval()
?
:) This is an interesting question. Let me go through this one step at a time. This will not be able to handle everything, but just functions with string parameters.
Here's a jsFiddle with some basic code: http://jsfiddle.net/Sqa8L/
Note that I haven't tested it at all, so use with utmost care.
Ideally, I'd recommend using a parser of some sort to get much more reliable results, but I think you can follow through on this answer once you've understood the general concept. So, the regex first:
var matchFnName = /^([^(]+)\(([^)]+)\)/.exec(str);
This would give you two matches, one for the function name, and the second with the entire parameter list. (unless you have complex expressions in there, in which case, it will fail :) ).
I've just split using the simple statement:
var paramList = paramListStr.split(',');
This will fail if any strings contain a ','. You will need a better parsing technique to handle this.
You would need to send an object that would respond to the function call, or it defaults to the global scope.
onObject[fnName].apply(onObject, paramList);
Look at apply here. Basically, what apply
does is call the function on the object supplied in the first argument onObject
, with an argument list passed in the second argument paramList
.
Hope this helps to get you started in the general direction.
Whichever solution you will use, it will either implicitly or explicitly call eval()
at javascript level or it's equivalent at the engine level.