-1

I have a String that contains a function as a String. This String is returned by the server:

var funcStr = "function() {
    console.log('this is a sample function');
}";

Is it possible to parse this String to a Function and execute it?

3
  • 2
    Yes its possible var fn = eval(funcStr);. Should you do this ever? NO. Also, note the unescaped quotes. Commented Mar 30, 2017 at 13:26
  • 1
    Side note: use single quotes for nested quotes. Commented Mar 30, 2017 at 13:28
  • 4
    Maybe you should consider fixing the server; that's a weird thing to do. Commented Mar 30, 2017 at 13:29

1 Answer 1

1

Yes, it is possible, but not a good idea. You use eval. This isn't the best to do for reasons too complex and opinion-based to get into here.

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

2 Comments

Please don't answer dupes. Flag for closure instead.
Why not both? :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.