Skip to main content
AllDevToolsHub
Back to all patterns

HTML Heading Tag Extraction

Extraction

Extracts HTML heading tags (h1-h6) and their text content.

/<h([1-6])[^>]*>(.*?)<\/h\1>/gi

How it works

This pattern matches HTML heading tags h1 through h6. The first capture group captures the heading level (1-6), and the second captures the text content. The backreference \1 ensures the closing tag matches the opening tag level.

Test Cases

Should Match

  • <h1>Main Title</h1>
  • <h2 class='subtitle'>Section</h2>

Should NOT Match

  • <h7>Invalid</h7>
  • <p>Paragraph</p>

Quick Summary

Extracts HTML heading tags (h1-h6) with their level and text content. Uses a backreference to ensure matching opening and closing tags. Case-insensitive and global flags for real-world HTML.

Key Takeaways

Key Takeaways

  • Capture group 1: heading level (1-6)
  • Capture group 2: heading text content
  • Backreference \1 ensures h2 closes with </h2>, not </h3>
  • Does not handle nested HTML inside headings, use a proper parser for that
Use Cases

When to use it

  • Extracting page headings for table-of-contents generation
  • Analyzing heading hierarchy in HTML documents
  • Scraping article titles from HTML pages
Watch out

Common Mistakes

  • Forgetting the case-insensitive flag, HTML headings can be uppercase in some documents
  • Expecting this to handle headings with nested HTML tags like <h2><a href='...'>Title</a></h2>
FAQ

HTML Heading Tag Extraction, Frequently Asked

How do I build a table of contents from headings?

Extract all headings with this pattern, then build a nested list based on heading levels.

What is the correct heading hierarchy?

Start with h1 for the page title, then h2 for sections, h3 for subsections. Never skip levels for accessibility.