How to get a functions's body as string?

后端 未结 4 1424
不思量自难忘°
不思量自难忘° 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 !

    0 讨论(0)
  • 2020-12-06 17:33

    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

    0 讨论(0)
  • 2020-12-06 17:48

    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.

    0 讨论(0)
  • 2020-12-06 17:54

    If you're going to do something ugly, do it with regex:

    A.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
    
    0 讨论(0)
提交回复
热议问题