Regex 如何获得箭头函数';谁的身体像一根绳子?
如何将代码作为arrow函数的Regex 如何获得箭头函数';谁的身体像一根绳子?,regex,reflection,ecmascript-6,arrow-functions,Regex,Reflection,Ecmascript 6,Arrow Functions,如何将代码作为arrow函数的{}之间的字符串获取 var myFn=(arg1,..,argN)=>{ /** *Want to parse * ONLY which is between { and } * of arrow function */ }; 如果很容易解析简单函数的主体:myFn.toString().match(/function[^{]+\{([\s\s]*)\}
{}
之间的字符串获取
var myFn=(arg1,..,argN)=>{
/**
*Want to parse
* ONLY which is between { and }
* of arrow function
*/
};
如果很容易解析简单函数的主体:myFn.toString().match(/function[^{]+\{([\s\s]*)\}$/)[1];
就足够了。但是,Arrow函数的定义中不包含函数
关键字。这是我的尝试:
函数getArrowFunctionBody(f){
常量matches=f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){([\s\s]*)}?$/);
如果(!匹配){
返回null;
}
const firstPass=匹配[1];
//需要,因为RegExp不处理最后一个“}”。
康斯特第二通行证=
(firstPass.match(/{/g)| |[])。长度===(firstPass.match(/}/g)| |[])。长度-1?
firstPass.slice(0,firstPass.lastIndexOf('}'):
第一关
返回第二通行证;
}
常数K=(x)=>(y)=>x;
常数I=(x)=>(x);
常数V=(x)=>(y)=>(z)=>z(x)(y);
常数f=(a,b)=>{
常数c=a+b;
返回c;
};
const empty=()=>{return undefined;};
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));
log(getArrowFunctionBody(空))代码>我来找一个解决方案,因为我不想写一个,但我没有被公认的答案说服。对于任何对ES6 1-liner感兴趣的人,我编写了这个方法,它可以处理我需要的所有情况——普通函数和箭头函数
const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4');
字符串是独立的,还是更大文本的一部分?为什么要这样做?@FelixKling:For this=>为什么不使用解析器就试图解析JS?How to do parser?适用于所有情况,除非没有像()=>{/*…*/}
@AbdennourTOUMI这样的参数。我已经更新了答案。