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()
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 !
Currently, developers are using arrow functions with the new releases of Ecmascript.
Hence, I would like to share the answer here which is the answer of Frank
function getArrowFunctionBody(f) {
const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
if (!matches) {
return null;
}
const firstPass = matches[1];
// Needed because the RegExp doesn't handle the last '}'.
const secondPass =
(firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1 ?
firstPass.slice(0, firstPass.lastIndexOf('}')) :
firstPass
return secondPass;
}
const K = (x) => (y) => x;
const I = (x) => (x);
const V = (x) => (y) => (z) => z(x)(y);
const f = (a, b) => {
const c = a + b;
return c;
};
const empty = () => { return undefined; };
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));
console.log(getArrowFunctionBody(empty));
Original question here
You could just stringify the function and extract the body by removing everything else:
A.toString().replace(/^function\s*\S+\s*\([^)]*\)\s*\{|\}$/g, "");
However, there is no good reason to do that and toString actually doesn't work in all environments.
If you're going to do something ugly, do it with regex:
A.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];