HTML Tag Extraction
Extracts opening HTML tags and their tag names from an HTML string.
/<([a-zA-Z][a-zA-Z0-9]*)(?:\s[^>]*)?>/gHow it works
This pattern matches opening HTML tags (not self-closing or closing tags). The first capture group captures the tag name. It handles tags with attributes. Note: for robust HTML parsing, always use a proper HTML parser, regex is not suitable for parsing nested or malformed HTML.
Test Cases
Should Match
- <div>
- <a href='https://example.com'>
- <input type='text' id='name'>
Should NOT Match
- </div>
- <!-- comment -->
- <br/>
Quick Summary
Extracts opening HTML tags and their tag names. Capture group 1 is the tag name. Use the global flag to find all tags. For production HTML parsing, use a proper parser like cheerio or the browser's DOMParser, regex cannot handle nested or malformed HTML reliably.
Key Takeaways
- Matches opening tags only, not closing tags (</div>) or self-closing tags (<br/>)
- Capture group 1: the tag name (div, a, input, etc.)
- Does not parse attribute values, use a proper HTML parser for that
- Regex-based HTML parsing breaks on malformed, nested, or script-embedded HTML
When to use it
- Quick extraction of tag names from simple, known-good HTML snippets
- Counting tag occurrences in a template file
- Detecting specific tags in user-submitted content for sanitization hints
Common Mistakes
- Using regex to parse full HTML documents, use cheerio (Node.js) or DOMParser (browser) instead
- Expecting this to handle self-closing tags like <br/> or <img/>
HTML Tag Extraction, Frequently Asked
Why shouldn't I parse HTML with regex?
HTML is not a regular language. Nested tags, optional closing tags, and malformed markup make regex-based parsing unreliable. Use a proper parser.
What library should I use to parse HTML in Node.js?
cheerio is the most popular: it provides a jQuery-like API for server-side HTML parsing and manipulation.