🔍Regex Recipes

Markdown Heading Detection

Detect markdown headings with ATX-style # syntax.

Pattern

^#{1,6}\s+.+$

Explanation

Matches markdown headings: 1-6 hash symbols, followed by space, then heading text.

Examples

H1
Input
# Main Title
Output
✓ Match
H3
Input
### Subsection
Output
✓ Match
H6
Input
###### Smallest
Output
✓ Match
Not heading
Input
#tag without space
Output
✗ No match
Too many #
Input
####### Invalid
Output
✗ No match

Code Examples

JavaScript
const headingRegex = /^(#{1,6})\s+(.+)$/gm;

// Extract all headings
const markdown = `
# Title
## Section 1
### Subsection
## Section 2
`;

const headings = [...markdown.matchAll(headingRegex)]
  .map(([, hashes, text]) => ({
    level: hashes.length,
    text: text.trim()
  }));
// Result: [
//   { level: 1, text: 'Title' },
//   { level: 2, text: 'Section 1' },
//   ...
// ]

Try it Now

💡 Tips

  • Capture level with (#{1,6}) group
  • Use multiline flag (m) for multiple headings
  • Consider Setext style: ===== or -----
  • For full markdown parsing, use marked or remark

⚠️ Common Pitfalls

  • Only detects ATX-style (#), not Setext-style (underlines)
  • Does not validate heading hierarchy
  • May want to trim heading text
  • Use markdown parser for full features