Skip to content

Extracting headings from content #493

Answered by rpaul-stripe
doncezart asked this question in Q&A
Discussion options

You must be logged in to vote

Here's an example that shows how to parse the document, iterate over the AST, identify the headings, and extract the heading text, level, and ID:

import Markdoc from "@markdoc/markdoc";

const example = `
# This is a test {% #test-1 %}

## This is another test

### One more test {% #test-3 %}
`;

const ast = Markdoc.parse(example);

function getNodeText(node) {
  let content = '';
  for (const {type, attributes} of node.walk())
    if (type === 'text' && typeof attributes.content === 'string')
      content += attributes.content;
  return content;
}

function* getTOC(ast) {
  for (const node of ast.walk())
    if (node.type === 'heading')
      yield {content: getNodeText(node), attributes: 

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@mfix-stripe
Comment options

Answer selected by mfix-stripe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants