Parsing Metadata Inside of Markdown Using JavaScript Without Any Dependencies

In a recent project, I worked with Markdown files that contained metadata at the top for blog posts. I needed to parse the Markdown with JavaScript and make a set of key/value pairs.

As you can see, the metadata is encapsulated in – – – with the metadata contained within.

// Function to parse metadata from a markdown file
const parseMarkdownMetadata = markdown => {
  // Regular expression to match metadata at the beginning of the file
  const metadataRegex = /^---([\\s\\S]\*?)---/;
  const metadataMatch = markdown.match(metadataRegex);

  // If there is no metadata, return an empty object
  if (!metadataMatch) {
    return {};
  }

  // Split the metadata into lines
  const metadataLines = metadataMatch[1].split("\\n");

  // Use reduce to accumulate the metadata as an object
  const metadata = metadataLines.reduce((acc, line) => {
    // Split the line into key-value pairs
    const [key, value] = line.split(":").map(part => part.trim());
    // If the line is not empty add the key-value pair to the metadata object
    if(key) acc[key] = value;
    return acc;
  }, {});

  // Return the metadata object
  return metadata;
};

You can call this function and pass in the markdown file content. It will return an object with the metadata.

const markdown = \`---
title: My Blog Post
author: John Doe
date: 2021-01-01
---
# My Blog Post
This is the content of my blog post.\`;
var metadata = parseMarkdownMetadata(markdown);
console.log(metadata);
// Output: { title: "My Blog Post", author: "John Doe", date: "2021-01-01" }

The great thing about this solution is it requires no additional libraries. It’s all plain Javascript.