1

I am trying to remove comments from HTML in Javascript but not working correctly. I need only plain HTML except comments

let sourceHTML = document.querySelector(".mySelector").innerHTML;
sourceHTML = sourceHTML.replace(/<--!(?:.|\n)*?-->/gm, '');
console.log(sourceHTML);
<div class="mySelector">
    <!--Main content -->
    <p>HTML content...</p>
</div>

Can anyone help me?

1
  • 1
    Let the dom do the parsing. It is a better parser than regex for html. jsfiddle.net/obz19hwy A comment is a node and has nodeType = 8 Commented Apr 13, 2019 at 6:58

1 Answer 1

3

You have ! character at wrong place in your regex

/<--!(?:.|\n)*?-->/
    |________________  This should be before `--` i.e:-  !--

let sourceHTML = document.querySelector(".mySelector").innerHTML;
sourceHTML = sourceHTML.replace(/<!--(?:.|\n)*?-->/gm, '');
console.log(sourceHTML);
<div class="mySelector">
    <!--Main content -->
    <p>HTML content...</p>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.