0

I have a function:

var greet = function (name) {
 console.log("Hi " + name);
}

If I have a string "greet('eric')" is it possible to convert it to a function call passing "eric" as argument?

asked Apr 20, 2011 at 6:09

5 Answers 5

2
answered Apr 20, 2011 at 6:10
Sign up to request clarification or add additional context in comments.

4 Comments

Oh totally forgot eval(). Isn't it the other way around, its evil?
@weng Eval is only evil if you misuse it
The call of a thousand screaming virgins tearing at their flesh accompany your answer.
W3Schools bashing seems to be fashionable nowadays. They may be wrong in many aspects, but in their days (w3schools started in 1999) they were a great source of information to many. Maybe they'll catch up someday.
2

You, me, him her and them fWord('ing') hate eval. There's always another way.

callMethod = function(def) {
 //all the variables are function references
 var approvedMethods = {greet: greet, love: love, marry: marry, murder: murder, suicide: suicide},
 split = def.split(/\(/); //split[0] contains function name, split[1] contains (unsplit) parameters
 //replace last ) and all possible string detonators left-over
 split[1] = split[1].replace(/\)$/, '').replace(/[\'\"]/g, '').split(','); //contains list of params
 if (!approvedMethods[split[0]])
 return 'No such function.';
 approvedMethods[split[0]].apply(window, split[1]);
}
//Called like this:
callMethod("greet('eric')");

Replace window reference with whatever.

answered Apr 20, 2011 at 6:42

Comments

1

I'm not sure I've understood your question correctly, but are you looking for the eval() function?

eval("greet('eric')");
answered Apr 20, 2011 at 6:12

Comments

1

It is as easy as typing

eval("greet('eric')");
answered Apr 20, 2011 at 6:13

Comments

1

without eval

var greet = function (name) {
 console.log("Hi " + name);
 },
 greetstr = 'greet("Eric")';
var greeter = greetstr.split('("');
window[greeter[0]]( greeter[1].replace(/\)|"/g,'') );

Bottom line 1: use eval with care
Bottom line 2: avoid constructions like this.

Just to be sure you have all possibilities @ your disposal: setTimeout(greetstr,0);
Mmmm, there is an eval in there somewhere ;)

answered Apr 20, 2011 at 6:23

1 Comment

I guess eval() indeed is my friend in this case=)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.