字符串中的函数名称

时间:2018-12-01 10:13:05

标签: javascript

如何从JavaScript中的字符串获取所有函数名称?

假设我的字符串是:

var test = "function hello(){} function world(count){ alert('Count:'+count)}"

我如何获取函数名称(字符串的内容是随机的):

hello
world

有人可以告诉我如何用纯JavaScript做到吗?

2 个答案:

答案 0 :(得分:4)

使用自定义代码解析JavaScript不是一件容易的事。考虑包含alert("this is not a function haha() {}")的代码实例。

但是,如果您对简单,不完美的方法感到满意,则可以使用正则表达式,如下所示:

function getFunctionNames(src) {
    var re = /\bfunction\s*\*?\s*\b(\w+)\s*\(/g,
        match,
        names = [];
    while(match = re.exec(test)) names.push(match[1]);
    return names;
}

var test = "function hello(){} function* world(count){ alert('Count:'+count}";
console.log(getFunctionNames(test));

答案 1 :(得分:3)

如果您想使用它来防止注射,对您来说是个坏消息。

通过任何方式,您都可以使用正则表达式查找函数名称

var test = "function hello(){} function world(count){ alert('Count:'+count}"
var res = test.match(/(?<=(function\s))(\w+)/g)

console.log(res)