Generate Table Of Content From Markdown

Creating a Table of Contents manually is a very intimidating task. So in this post, I will share my code snippet that will help you to dynamically generate a Table of Contents from Markdown files programmatically.

	type TableItem = { level: number, heading: string };

function extractTableOfContents(markdownContent: string): TableItem[] {
  // Regular expression to match markdown headings
  const regXHeader = /#{1,6}.+/g;

  // Match all headings in the markdown content
  const matchedHeadings = markdownContent.match(regXHeader) || [];

  // Map each heading to a TableItem object
  return matchedHeadings.map((headingText) => {
    // Count the number of '#' to determine the heading level
    // Subtract 2 because we start from the 2nd heading and 1 for the extra heading text
    const headingLevel = headingText.split("#").length - 1 - 2;

    // Remove '#' from the heading text
    const cleanedHeadingText = headingText.replace(/#{1,6}/, "").trim();

    return {
      level: headingLevel,
      heading: cleanedHeadingText,
    };
  });
}

If you implement the provided code, you'll be able to generate an output like the one shown below. This output can then be utilized in any way you prefer.

	// 0 - h1
// 5 - h6
[
  {
    "level": 0,
    "heading": "Overview"
  },
  {
    "level": 1,
    "heading": "Importance of bar"
  },
  {
    "level": 1,
    "heading": "Utilizing bar"
  },
  {
    "level": 0,
    "heading": "Alternative Methods"
  },
  {
    "level": 2,
    "heading": "Future Steps"
  },
  {
    "level": 0,
    "heading": "Conclusion"
  }
]

I hope this post will help you to generate a Table of Contents from Markdown files. If you have any questions or suggestions, feel free to leave a comment below.