1

String is as follows: "foo('argument1','argument2')"

How can I execute this function as javascript without using eval? I know you can use

window[func](arguments),

but the arguments are part of the string. I tried using regex but I'm not sure how to do it considering javascript doesn't have lookbehinds. Any suggestions?

5
  • Can you explain why you are trying to do this? From what you have said, eval is your only real option, but more info would help. Commented Jul 5, 2013 at 19:06
  • One should ask, how is this string being made in the first place? and can't you construct something more helpful there, instead (e.g. JSON) Commented Jul 5, 2013 at 19:11
  • If you can convert the arguments to an array, you can use window[func].apply(null, args). Commented Jul 5, 2013 at 19:19
  • @RocketHazmat Did you notice that your comment was part of my answer ? Commented Jul 5, 2013 at 19:21
  • @dystroy: I just did! :-) Commented Jul 5, 2013 at 19:22

2 Answers 2

1

You can use this :

var s = "foo('argument1','argument2', 5, true)";
var m = s.match(/([^(]+)\(([^)]+)\)/);
if (m) {
   var f = window[m[1]];
   var args = m[2].split(',').map(function(v){
     return JSON.parse(v.trim().replace(/^'/,'"').replace(/'$/,'"'))
   });
   f.apply(null,args);
}

Demonstration (open the console)

Note that this works only for primitive arguments. If you want to handle other types of arguments without eval, you'd better define what types you want to handle.

Sign up to request clarification or add additional context in comments.

2 Comments

If some part of my answer isn't clear, please ask and I'll explain.
It's clear. The purpose is so I can have an inline custom event (ie: <button onmyevent="dothis('argument1')">Button</button>). I use jQuery to tell the event to fire, but I needed a way to execute the string given by the onmyevent attribute.
0

There are several ways of doing it, one has already been given by dystroy.

A slightly simpler way would be this:

var args = "foo('argument1','argument2')".split(/[()',]+/).slice(0,-1)
Function.prototype.call.apply(window[args[0]],args)

2 Comments

I like this. Very very nice.
Did you realize the main reason it's shorter is that it only handles strings ?

Your Answer

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.