0

I am trying to remove unnecessary Line Comments from html & css. I've Found a regex to remove comments like these:

/* Write your comments here */

but what Im looking for is a regex to Multi Line Comments like these:

<!-- Write your comments here 
Second line
third Line
-->

Currently Using this code to remove the single line comments:

<!--[^\[].*-->

Any assistance would be greatly appreciated

1 Answers1

0

Better to generate a temporary DOM element and iterating over all the nodes recursively remove the comment nodes.

var str = `
<div>
test
<!-- test comment -->
<!-- test comment -->
test

<!-- 
test comment
multiline
-->
</div>`;

// generate div element
var temp = document.createElement('div');
// set HTML content
temp.innerHTML = str;

function removeEle(e) {
  // convert child nodes into array
  Array.from(e.childNodes)
    // iterate over nodes
    .forEach(function(ele) {
      // if node type is comment then remove it
      if (ele.nodeType === 8) e.removeChild(ele);
      // if node is an element then call it recursively
      else if (ele.nodeType === 1) removeEle(ele);
    })
}

removeEle(temp);

console.log(temp.innerHTML);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188