Remove HTML comments with Regex, in Javascript

This is based off Aurielle Perlmann's answer, it supports all cases (single-line, multi-line, un-terminated, and nested comments):

/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g

https://regex101.com/r/az8Lu6/1

regex101 output


The regex /<!--[\s\S]*?-->/g should work.

You're going to kill escaping text spans in CDATA blocks.

E.g.

<script><!-- notACommentHere() --></script>

and literal text in formatted code blocks

<xmp>I'm demoing HTML <!-- comments --></xmp>

<textarea><!-- Not a comment either --></textarea>

EDIT:

This also won't prevent new comments from being introduced as in

<!-<!-- A comment -->- not comment text -->

which after one round of that regexp would become

<!-- not comment text -->

If this is a problem, you can escape < that are not part of a comment or tag (complicated to get right) or you can loop and replace as above until the string settles down.


Here's a regex that will match comments including psuedo-comments and unclosed comments per the HTML-5 spec. The CDATA section are only strictly allowed in foreign XML. This suffers the same caveats as above.

var COMMENT_PSEUDO_COMMENT_OR_LT_BANG = new RegExp(
    '<!--[\\s\\S]*?(?:-->)?'
    + '<!---+>?'  // A comment with no body
    + '|<!(?![dD][oO][cC][tT][yY][pP][eE]|\\[CDATA\\[)[^>]*>?'
    + '|<[?][^>]*>?',  // A pseudo-comment
    'g');