Подтвердить что ты не робот

Как получить тело функции как строку?

Я хочу знать, как преобразовать тело функции в строку?

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???
4b9b3361

Ответ 1

Если вы собираетесь сделать что-то некрасивое, сделайте это с помощью регулярного выражения:

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

Ответ 2

Вы можете просто подкрепить функцию и извлечь тело, удалив все остальное:

A.toString().replace(/^function\s*\S+\s*\([^)]*\)\s*\{|\}$/g, "");

Однако для этого нет веских оснований, и toString фактически не работает во всех средах.

Ответ 3

В настоящее время разработчики используют функции со стрелками в новых версиях Ecmascript.

Следовательно, я хотел бы поделиться ответом здесь, который является ответом Фрэнка

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

Ответ 4

Не используйте регулярные выражения.

const getBody = (string) => {
  const bodyStart = string.indexOf("{") + 1
  const bodyEnd = string.lastIndexOf("}")
  return string.substring(bodyStart, bodyEnd)
}

const f = () => { return 'yo' }
const g = function (some, params) { return 'hi' }

console.log(getBody(f.toString()))
console.log(getBody(g.toString()))