views:

50

answers:

3

Hello, I have a function e.g.

var test = function () {alert(1);}

How can I get the body of this function?

I assume that the only way is to parse the result of test.toString() method, but is there any other way? If parsing is the only way, what will be the regex to get to body? (help with the regex is extremly needed, because I am not familiar with them)

+1  A: 

"function decompilation" — a process of getting string representation of a Function object.

Function decompilation is generally recommended against, as it is a non-standard part of the language, and as a result, leads to code being non-interoperable and potentially error-prone.

@kangax on comp.lang.javascript

galambalazs
Though it is not recommended, I think this can be useful when you want to display the code that is being ran (e.g. for a javascript tutorial)
m_oLogin
the ones who ask on SO are generally not the ones who write tutorials. Depending on non-standard features **in production use** will result in hard-to-debug code aka kiss-of-death.
galambalazs
A: 

Try this:

/\{(\s*?.*?)*?\}/g.exec(test.toString())[0]

test.toString() will hold your entire declaration.

/{(\s*?.?)?}/g will match everything between your braces

m_oLogin
Non-greedy is exactly what you *don't* want here (since there may be nested blocks). If you were going down this route, you'd do `/\{.*\}/s` or `\{(?s:.*)\}` - but simpler to just strip based on `{` and `}` as in answer by polygenelubricants.
Peter Boughton
that's true. thanks for pointing it out
m_oLogin
+2  A: 
polygenelubricants