Generate TOC from Markdown

Generate TOC from Markdown

It generate the Table of Content from Markdown Content

getTableOfContents.ts

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(),
      };
    });
  }

The above Code will generate the outpul like this:

// 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"
    }
]