JavaScript Regex to replace YAML frontmatter

272 views Asked by At

I'm building a nodejs package that reads the YAML front matter from a file. I used the YAML package to get the YAML, convert it to JSON and make my changes to it.

Now I want to be able to replace the whole frontmatter but can't find the RegEx to do so.

templateFile = templateFile.replace(SOME-REGEX-EXPRESSION, YAML.stringify(frontmatter)

What RegEx can I use here to accomplish this?

1

There are 1 answers

3
Destroy666 On

New answer to modified question

/---\n.*?\n---/s

This regex matches frontmatter including --- start and end. Compared to the old regex you just need to not use lookaheads.

Old answer

You can use this to match frontmatter without ---:

/(?<=---\n).*?(?=\n---)/s

Breakdown:

  • (?<=---\n) - positive lookbehind to match --- followed by new line
  • .*? - lazily match anything
  • (?=\n---) - positive lookahead to match --- preceded by new line
  • s - flag for dot to also match new lines

Demo