Markdown Frontmatter Parser
Split Markdown frontmatter from the body and parse flat YAML scalars, with BOM handling and clear error messages.
Code
export interface FrontmatterResult<T extends Record<string, unknown>> {
attributes: T;
body: string;
rawFrontmatter: string;
}
function parseScalar(raw: string): unknown {
if (raw === "" || raw === "~" || raw === "null") return null;
if (raw === "true" || raw === "false") return raw === "true";
if (/^-?\d+(?:\.\d+)?$/.test(raw)) return Number(raw);
if (raw.startsWith('"') && raw.endsWith('"')) {
return raw.slice(1, -1).replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
}
if (raw.startsWith("'") && raw.endsWith("'")) {
return raw.slice(1, -1).replace(/''/g, "'");
}
return raw;
}
export function parseFrontmatter<T extends Record<string, unknown> = Record<string, unknown>>(
markdown: string,
): FrontmatterResult<T> {
if (typeof markdown !== "string") throw new TypeError("markdown must be a string");
const normalized = markdown.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
if (!normalized.startsWith("---\n")) {
throw new SyntaxError("frontmatter must start with a --- line");
}
const closing = normalized.indexOf("\n---", 4);
if (closing === -1) throw new SyntaxError("missing closing --- delimiter");
const rawFrontmatter = normalized.slice(4, closing);
const body = normalized.slice(closing + 4).replace(/^\n/, "");
const attributes: Record<string, unknown> = {};
for (const line of rawFrontmatter.split("\n")) {
if (line.trim() === "" || line.trimStart().startsWith("#")) continue;
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
if (!match) throw new SyntaxError("unsupported frontmatter line: " + line);
attributes[match[1]!] = parseScalar(match[2]!.trim());
}
return { attributes: attributes as T, body, rawFrontmatter };
}What the code does
Markdown Frontmatter Parser keeps everything in the function parseScalar.
Repetition is confined to for (const line of rawFrontmatter.split("\n")) — the rest of the file is straight-line. Invalid states are rejected up front: it throws TypeError and SyntaxError instead of continuing with bad data.
The result comes back as an object carrying T, body.
Caveats
- The guard
raw === "" || raw === "~" || raw === "null"short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
parseFrontmatter is the public entry point; everything else in the file exists to support it.
The call returns T, body — destructure what you need at the call site.
Key statements
return raw.slice(1, -1).replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
if (typeof markdown !== "string") throw new TypeError("markdown must be a string");
if (closing === -1) throw new SyntaxError("missing closing --- delimiter");
Interactive Tools for This Topic
YAML Frontmatter ExtractorExtract the YAML frontmatter block from Markdown documents and parse scalars and simple lists into a JSON metadata object.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- Does `parseFrontmatter` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- What does the snippet do with malformed data?
- Validation comes first — `TypeError` and `SyntaxError` marks the failure at `raw === "" || raw === "~" || raw === "null"`, before any partial work happens.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `parseScalar` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.