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 getTableOfContents(markdown: string): TableItem[] {
    const regXHeader = /#{1,6}.+/g;
    const headingArray = markdown.match(regXHeader)
      ? markdown.match(regXHeader)
      : [];
    return headingArray?.map((heading) => {
      return {
        level: heading.split("#").length - 1 - 2, // we starts from the 2nd heading that's why we subtract 2 and 1 is extra heading text
        heading: heading.replace(/#{1,6}/, "").trim(),
      };
    });
  }

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": "Introduction"
    },
    {
        "level": 1,
        "heading": "Need of foo"
    },
    {
        "level": 1,
        "heading": "How to Use foo?"
    },
    {
        "level": 0,
        "heading": "Another approach"
    },
    {
        "level": 2,
        "heading": "What Next?"
    },
    {
        "level": 0,
        "heading": "Wrapping up"
    }
]
0
Subscribe to my newsletter

Read articles from Rajarshi Samaddar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rajarshi Samaddar
Rajarshi Samaddar

I create tailored web solutions, excel in product development, and code in multiple languages. My commitment is to deliver excellence, ensuring seamless user experiences for clients.