title: Extract only javascript from a script tag
body: <p>I would like to extract only javascript from script tags in a HTML document which I want to pass it to a JS parser like <a href="http://esprima.org/demo/parse.html" rel="nofollow">esprima</a>. I am using nodejs to write this application and have the content extracted from the script tag as a string. 
  The problem is when there are HTML comments in the javascript extracted from html documents which I want to remove. <br>
  <code>&lt;!-- var a; --&gt;</code> should be converted to <code>var a</code> <br>
  A simple removal of <code>&lt;--</code> and <code>--&gt;</code> does not work since it fails in the case <code>&lt;!-- if(j--&gt;0); --&gt;</code> where it removes the middle <code>--&gt;</code> <br>
  I would also like to remove identifiers like <code>[if !IE]</code> and <code>[endif]</code> which are sometimes found inside script tags. 
  I would also like to extract the JS inside CDATA segments. 
  <br>
  <code>&lt;![CDATA[ var a; ]]&gt;</code> should be converted to <code>var a</code> <br>
  Is all this possible using a regex or is something more required? <br>
  In short I would like to sanitize the JS from script tags so that I can safely pass it into a parser like esprima. <br>
  Thanks!</p>
  
  <p>EDIT: <br>
  Based on @user568109 's answer. This is the rough code that parses through HTML comments and CDATA segments inside script tags <br></p>
  
  <pre><code>var htmlparser = require("htmlparser2");
  var jstext = '';
  var parser = new htmlparser.Pavar htmlparser = require("htmlparser2");
  var jstext = '';
  var parser = new htmlparser.Parser({
  onopentag: function(name, attribs){
      if(name === "script" &amp;&amp; attribs.type === "text/javascript"){
          jstext = '';
          //console.log("JS! Hooray!");
      }
  },
  ontext: function(text) {
      jstext += text;
  },
  onclosetag: function(tagname) {
      if(tagname === "script") {
          console.log(jstext);
          jstext = '';
      }
  },
  oncomment : function(data) {
      if(jstext) {
          jstext += data;
      }
  }
  },  {
  xmlMode:true
  });
  parser.write(input);
  parser.end()
  </code></pre>