stripHtmlComments

by Hans PUFAL

HTML

<pre id="result">
  <!-- comment -- ??? -- comment -->
</pre>

JavaScript

function stripHtmlComments (html) {
  return html.replace (/<!--(.*?)-->|(<!--[^]{0,10})|(-->[^]{0,10})/g,
      function (m0, cmt, open, close) {
        if (open) throw 'Illegal HTML - no closing comment sequence ("-->")' +
                        ' for open at "' + open + '"';
        if (close) throw 'Illegal HTML - unexpected close comment at "' + close + '"';
        
        return '';         
      }).trim ();
};

document.getElementById ('result').innerHTML = JSON.stringify (
  [ 'abc', 
    'abc <!-- comments --> def', 
    'a <!-- 1 --> b <!-- 2 --> c'
  ].map (stripHtmlComments));