Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get function body text in JavaScript? [duplicate]

function derp() { a(); b(); c(); } 

derp.toString() will return "function derp() { a(); b(); c(); }", but I only need the body of the function, so "a(); b(); c();", because I can then evaluate the expression. Is it possible to do this in a cross-browser way?

like image 635
greepow Avatar asked Sep 01 '12 12:09

greepow


People also ask

How do you duplicate a function in JavaScript?

clone = function() { var newfun = new Function('return ' + this. toString())(); for (var key in this) newfun[key] = this[key]; return newfun; };

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

Which method is used to get a string equivalent of a function?

The toString() method returns a string representing the source code of the specified Function .


2 Answers

var entire = derp.toString();  var body = entire.slice(entire.indexOf("{") + 1, entire.lastIndexOf("}"));  console.log(body); // "a(); b(); c();" 

Please use the search, this is duplicate of this question

like image 129
divide by zero Avatar answered Oct 16 '22 20:10

divide by zero


Since you want the text between the first { and last }:

derp.toString().replace(/^[^{]*{\s*/,'').replace(/\s*}[^}]*$/,''); 

Note that I broke the replacement down into to regexes instead of one regex covering the whole thing (.replace(/^[^{]*{\s*([\d\D]*)\s*}[^}]*$/,'$1')) because it's much less memory-intensive.

like image 39
Niet the Dark Absol Avatar answered Oct 16 '22 20:10

Niet the Dark Absol