Generate TOC from Markdown
![Generate TOC from Markdown](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2F5ec749u0%2Fproduction%2F3f9db520fac64f9a23b2fa8ed980016ae231c645-800x800.png&w=128&q=75)
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"
}
]