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?

5 Answers 5

2

eval() is your friend ! http://www.w3schools.com/jsref/jsref_eval.asp

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.

Comments

1

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

eval("greet('eric')");

Comments

1

It is as easy as typing

eval("greet('eric')");

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 ;)

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.