Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a functions's body as string?

I want to know how to convert a function's body into a string?

function A(){
  alert(1);
}

output = eval(A).toString() // this will come with  function A(){  ~ }

//output of output -> function A(){ alert(1); }

//How can I make output into alert(1); only???
like image 209
Micah Avatar asked Feb 14 '13 23:02

Micah


1 Answers

Don't use a regexp.

const getBody = (string) => string.substring(
  string.indexOf("{") + 1,
  string.lastIndexOf("}")
)

const f = () => { return 'yo' }
const g = function (some, params) { return 'hi' }
const h = () => "boom"

console.log(getBody(f.toString()))
console.log(getBody(g.toString()))
console.log(getBody(h.toString())) // fail !
like image 110
Clemens Avatar answered Sep 19 '22 11:09

Clemens