javascript 45 lines · 9 steps

Parsing YAML-style frontmatter in JavaScript

A small parser that pulls a key-value header block off a Markdown document and coerces each value to its natural type.

Explained by highlit
1const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
2 
3function coerce(value) {
4 const trimmed = value.trim();
5 if (trimmed === '') return '';
6 if (trimmed === 'true') return true;
7 if (trimmed === 'false') return false;
8 if (trimmed === 'null' || trimmed === '~') return null;
9 
10 if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
11 (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
12 return trimmed.slice(1, -1);
13 }
14 
15 if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
16 const inner = trimmed.slice(1, -1).trim();
17 if (inner === '') return [];
18 return inner.split(',').map((item) => coerce(item));
19 }
20 
21 if (/^-?\d+$/.test(trimmed)) return parseInt(trimmed, 10);
22 if (/^-?\d*\.\d+$/.test(trimmed)) return parseFloat(trimmed);
23 
24 return trimmed;
25}
26 
27export function parseFrontmatter(markdown) {
28 const match = markdown.match(FRONTMATTER_RE);
29 if (!match) {
30 return { data: {}, content: markdown };
31 }
32 
33 const data = {};
34 for (const line of match[1].split(/\r?\n/)) {
35 if (!line.trim() || line.trimStart().startsWith('#')) continue;
36 
37 const sep = line.indexOf(':');
38 if (sep === -1) continue;
39 
40 const key = line.slice(0, sep).trim();
41 if (key) data[key] = coerce(line.slice(sep + 1));
42 }
43 
44 return { data, content: markdown.slice(match[0].length) };
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single anchored regex can both detect and slice off a structured header in one pass.
  2. 2Coercion functions turn raw strings into typed values by checking cheap, specific cases first.
  3. 3Recursing a coercion routine over split parts lets scalar logic handle nested structures like arrays for free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing YAML-style frontmatter in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code