如何将函数的主体作为字符串?

Mic*_*cah 10 javascript function

我想知道如何将函数体转换为字符串?

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???
Run Code Online (Sandbox Code Playgroud)

nra*_*itz 27

如果你要做一些丑陋的事情,那就用正则表达式来做:

A.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
Run Code Online (Sandbox Code Playgroud)

  • 我不同意OP的做法,但我确实同意:'如果你要做一些丑陋的事情(你可能也会)用正则表达式来做.= d (8认同)
  • "如果你要做一些丑陋的事情,那就用正则表达式来做:"本周报价! (3认同)

Cle*_*ens 5

不要使用正则表达式。

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 !
Run Code Online (Sandbox Code Playgroud)