MANN
MANN

Reputation: 3520

Javascript to parse string with 'function'

I have following string which needs to be parsed using JS.

function () {\n     MyClass.prototype.doSomethingFunction();\n       5-6 lines of coding\n  }

I tried parsing it, trimming whitespaces and newlines but nothing worked for me. Please let me know how can I get function name (doSomethingFunction) from the above string.

How I'm getting this string:

I have a queue where my functions are stored. Later in time my code picks a function from this queue (some logic here) and execute them. It works perfectly ok for me. But I just want to print the name of the function out of it! It's like '(classOBJ.myFunctionsQueue[n])()' is used to execute a function which is stored at nth location in myFunctionsQueue array. Make sense or I'm doing something wrong in here?

Thanks MANN

Upvotes: 1

Views: 3390

Answers (3)

bfavaretto
bfavaretto

Reputation: 71918

First, if you're executing functions stored as strings, you're probably doing it wrong (using eval or new Function(body)). Couldn't you use an object as the queue, with the function names as keys, and function references (not strings) as values? Like this:

var queue = {
    "funcName" : function() { /* do something */ },
    "otherFunc" : function() { /* do something else */ }
    /* etc. */
};

Then you can print all names an execute all function from a loop, for example:

for(var key in queue) {
    console.log(key); // function name
    queue[key]();     // execute function
}

Upvotes: 0

Bergi
Bergi

Reputation: 664484

I don't think it's the right approach for your application, but the current problem could be solved by something like

myFunctionString.split("\n").reduce(function(map, line) {
    if (/^\s*[^\s[\]]+\(\);?\s*$/.test(line))
        map.push(line.split(".").pop().replace(/\(\);?\s*$/, ""));
    return map;
}, []);
// returns an array of invoked method names

Upvotes: 0

Diode
Diode

Reputation: 25135

Try a reg expression matching like this

var str = "function() {\n MyClass.prototype.doSomethingFunction();\n 5 - 6 lines of coding\n}";

var matches = str.match(/prototype\.(.+?)\(\)/);
if(matches){
    alert(matches[1]);
}

Upvotes: 2

Related Questions