How to get a functions's body as string?

后端 未结 4 1427
不思量自难忘°
不思量自难忘° 2020-12-06 17:07

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()         


        
4条回答
  •  温柔的废话
    2020-12-06 17:33

    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 !

提交回复
热议问题