I need to extract an entire javascript function from a script file. I know the name of the function, but I don't know what the contents of the function may be. This function may be embedded within any number of closures.
I need to have two output values:
- The entire body of the named function that I'm finding in the input script.
- The full input script with the found named function removed.
So, assume I'm looking for the findMe
function in this input script:
function() {
function something(x,y) {
if (x == true) {
console.log ("Something says X is true");
// The regex should not find this:
console.log ("function findMe(z) { var a; }");
}
}
function findMe(z) {
if (z == true) {
console.log ("Something says Z is true");
}
}
findMe(true);
something(false,"hello");
}();
From this, I need the following two result values:
The extracted
findMe
scriptfunction findMe(z) { if (z == true) { console.log ("Something says Z is true"); } }
The input script with the
findMe
function removedfunction() { function something(x,y) { if (x == true) { console.log ("Something says X is true"); // The regex should not find this: console.log ("function findMe(z) { var a; }"); } } findMe(true); something(false,"hello"); }();
The problems I'm dealing with:
The body of the script to find could have any valid javascript code within it. The code or regex to find this script must be able to ignore values in strings, multiple nested block levels, and so forth.
If the function definition to find is specified inside of a string, it should be ignored.
Any advice on how to accomplish something like this?
Update:
It looks like regex is not the right way to do this. I'm open to pointers to parsers that could help me accomplish this. I'm looking at Jison, but would love to hear about anything else.