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)
不要使用正则表达式。
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)