Back to all patterns
HTML Comment Extraction
Extraction
Extracts HTML comments from an HTML string.
/<!--[\s\S]*?-->/gHow it works
HTML comments start with <!-- and end with -->. The [\s\S]*? pattern matches any character including newlines (non-greedy). The global flag finds all comments in a document.
Test Cases
Should Match
- <!-- This is a comment -->
- <!-- multi line comment -->
Should NOT Match
- // not a comment
- /* not html */
Quick Summary
Extracts HTML comments (<!-- ... -->) from HTML strings. Uses non-greedy matching to handle multiple comments correctly. Use the global flag to find all comments in a document.
Key Takeaways
Key Takeaways
- Non-greedy *? prevents matching from the first <!-- to the last --> in a document
- [\s\S] matches any character including newlines
- Use the global flag (g) to extract all comments
- For production HTML parsing, use a proper parser
Use Cases
When to use it
- Stripping HTML comments from templates before minification
- Extracting build annotations or metadata from HTML files
- Detecting sensitive information accidentally left in HTML comments
Watch out
Common Mistakes
- Using greedy .* instead of non-greedy .*?, greedy matching consumes everything between the first <!-- and last -->
- Using . instead of [\s\S], the dot does not match newlines by default
FAQ
HTML Comment Extraction, Frequently Asked
How do I remove all HTML comments from a string?
str.replace(/<!--[\s\S]*?-->/g, '')
Can HTML comments contain --?
No. The HTML spec forbids -- inside comments. Some parsers are lenient, but it is invalid HTML.