38
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?

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
greepow
  • 6,353
  • 4
  • 15
  • 8

5 Answers5

55
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

Community
  • 1
  • 1
divide by zero
  • 2,300
  • 5
  • 21
  • 34
10

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.

Pierre C.
  • 1,433
  • 2
  • 14
  • 27
Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
4

NOTE: The accepted answer depends on the interpreter not doing crazy things like throwing back comments between 'function' and '{'. IE8 will happily do this:

>>var x = function /* this is a counter-example { */ () {return "of the genre"};
>>x.toString();
"function /* this is a counter-example { */ () {return "of the genre"}"
Ian
  • 49
  • 1
  • 1
3

A single-line, short regex example:

var body = f.toString().match(/^[^{]+\{(.*?)\}$/)[1];

If you want to, eventually, eval the script, and assuming the function takes no parameters, this should be a tiny bit faster:

var body = '(' + f.toString() + ')()';
K3---rnc
  • 6,104
  • 2
  • 30
  • 44
  • Turning it into an IIFE statement for evaluation is the most robust solution if the function takes in no arguments. Works with ES6 arrow function syntax too. – Shi Ling May 08 '18 at 09:51
2

You need something like this:

var content = derp.toString();
var body = content.match(/{[\w\W]*}/);
body = body.slice(1, body.length - 1);

console.log(body); // a(); b(); c();
sdgluck
  • 21,802
  • 5
  • 67
  • 87
micnic
  • 10,168
  • 5
  • 41
  • 53