45
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
  • 795,719
  • 175
  • 1,089
  • 1,143
greepow
  • 7,003
  • 4
  • 17
  • 8

5 Answers5

58
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,340
  • 5
  • 23
  • 34
11

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,591
  • 2
  • 16
  • 29
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
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,717
  • 3
  • 31
  • 46
  • 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
  • 24,894
  • 8
  • 75
  • 90
micnic
  • 10,915
  • 5
  • 44
  • 55