Skip to content

Instantly share code, notes, and snippets.

@tol-is
Last active January 6, 2022 20:35
Show Gist options
  • Save tol-is/dcf6656a4d241ca44dab9367d33b8b11 to your computer and use it in GitHub Desktop.
Save tol-is/dcf6656a4d241ca44dab9367d33b8b11 to your computer and use it in GitHub Desktop.
Get table of contents from markdown
const getToc = (source: string) =>
source
.split("\n")
.map((line) => {
const matches = line.match(/^#+[\s]+/);
return matches
? {
level: matches[0].trim().length,
heading: line.replace(matches[0], "").trim(),
}
: false;
})
.filter(Boolean);
const markdown = `# Heading One\n## Heading Two\n ##Should not Match\n ## # Only the first parth should match \n ### Heading Three`;
const toc = getToc(markdown);
/*
Expecting
[
{
level: 1,
heading: "Heading One"
},
{
level: 2,
heading: "Heading Two"
},
{
level: 2,
heading: "# Only the first parth should match"
},
{
level: 3,
heading: "Heading Three"
}
];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment