frontmatter

tcmts.content.frontmatter · #h7hjs4dx · function · runs anywhere

A Markdown file's frontmatter, as YAML between --- lines at its top, and the text under it. A file without frontmatter has no data ({}).

import { parse as parseYaml } from "yaml";

export function frontmatter(text: string): { data: unknown; body: string } {
  const m = /^---\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/.exec(text);
  if (!m) return { data: {}, body: text };
  return { data: parseYaml(m[1] ?? "") ?? {}, body: text.slice(m[0].length).replace(/^\r?\n/, "") };
}

used by