- 方法一:正则
/**
* 判定是否是函数字符串
* @param str 字符串
*/
const isFunctionString = (str: string): boolean => {
const functionPattern = /^\s*function\s+\w+\s*\([^)]*\)\s*\{/;
const arrowFunctionPattern = /^\s*\(?[\s\S]*\)?\s*=>/;
return functionPattern.test(str) || arrowFunctionPattern.test(str);
};
- 方法二:创建一个函数,判定是否抛出异常
/**
* 判定是否是函数字符串
* @param str 字符串
*/
const isFunctionString = (str: string): boolean => {
try {
const fn = new Function(`return ${str}`)();
return isFunction(fn);
} catch (e) {
return false;
}
};