← Back to all snippets
JAVASCRIPT

Extract Markdown Headings and Their Levels

Discover a regular expression to efficiently parse Markdown content, extracting all headings (H1-H6) along with their corresponding heading levels for dynamic table of contents generation.

function extractMarkdownHeadings(markdown) {
  const headings = [];
  const regex = /^(#{1,6})\s(.+)$/gm;
  let match;
  while ((match = regex.exec(markdown)) !== null) {
    headings.push({
      level: match[1].length,
      text: match[2].trim()
    });
  }
  return headings;
}
How it works: This snippet utilizes a global, multiline regular expression to scan Markdown text for lines that begin with one to six hash symbols followed by a space. It captures both the hash symbols (to determine the heading level) and the heading text itself, returning them as an array of structured objects useful for building navigation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs