title: How to to extract a javascript function from a javascript file
body: <p>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.</p>
  
  <p>I need to have two output values:</p>
  
  <ol>
  <li>The entire body of the named function that I'm finding in the input script.</li>
  <li>The full input script with the found named function removed.</li>
  </ol>
  
  <p>So, assume I'm looking for the <code>findMe</code> function in this input script:</p>
  
  <pre><code>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");
  }();
  </code></pre>
  
  <p>From this, I need the following two result values:</p>
  
  <ol>
  <li><p>The extracted <code>findMe</code> script</p>
  
  <pre><code>function findMe(z) {
    if (z == true) {
      console.log ("Something says Z is true");
    }
  }
  </code></pre></li>
  <li><p>The input script with the <code>findMe</code> function removed</p>
  
  <pre><code>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; }");
      }
    }
    findMe(true);
    something(false,"hello");
  }();
  </code></pre></li>
  </ol>
  
  <p>The problems I'm dealing with:</p>
  
  <ol>
  <li><p>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.</p></li>
  <li><p>If the function definition to find is specified inside of a string, it should be ignored.</p></li>
  </ol>
  
  <p>Any advice on how to accomplish something like this?</p>
  
  <p>Update:</p>
  
  <p>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 <a href="http://zaach.github.com/jison/" rel="noreferrer">Jison</a>, but would love to hear about anything else.</p>