Regex to Remove HTML Comments

All patterns
Replace15 chars · /g

Regex to Remove HTML Comments

Use this in cleanup scripts when you need to strip comment blocks from HTML exports or email templates.

The expression

/<!--[\s\S]*?-->/g

How to read it

\s matches any whitespace, including tabs and newlines.

gglobal — keep going after the first match instead of stopping

Find matches in your own text

no input
Try:

This expression is unanchored, so it finds every occurrence anywhere in the text. Highlighted runs are what a replace call would rewrite.

Examples, checked in your browser

4/4 verified

<!-- note -->

Matches.

<div><!-- remove me --></div>

Matches.

<div>No comments</div>

No match — this is the kind of input the pattern rejects.

<!DOCTYPE html>

No match — this is the kind of input the pattern rejects.

Use it in code

3 languages
JavaScript
const regex = /<!--[\s\S]*?-->/g;
regex.test(input);
Python
import re
pattern = re.compile(r"<!--[\s\S]*?-->")
bool(pattern.search(input))
Go
re := regexp.MustCompile("<!--[\\s\\S]*?-->")
matched := re.MatchString(input)

Other replace patterns

3
GroupReplace
Flags/g
Examples4
SafetyOK