简体   繁体   中英

Javascript Regex for YAML Front End Matter

I'm using a framework to render Markdown into HTML - but it doesn't respect YAML front end matter. It simply renders it as two <hr> and then the text between as a string in a <p> .

I wanted to create a plugin for the framework that would be able to render any Front End Matter (if it was present).

I've tried researching, but can't seem to find any information on how to match on the two --- needed.

I've tried creating my own Regex: https://regex101.com/r/ZmKyvP/2 but I can't seem to get the information between the --- . I seem to only match on those items.

Is there an easy way to be able to convert it into JSON?

Markdown

---
title: My awesome blog
date: 2020-06-30
tags: dogs,doggo,pupper,floofer,woofters
description: tl;dr
---

Don't capture me!

Regex

// current regex
/^(---)(.*)(---)$/g

Hopeful output

{
  "title": "My awesome blog",
  "date": "2020-06-30",
  "tags": ["dogs","doggo","pupper","floofer","woofters"],
  "description": "tl;dr"
}

Since you're already using javascript why not use some javaScript string manipulation to isolate the string you wish to work with?

function stringModification(){
const tango = "---";
var yourText = "---\ntitle: My awesome blog\ndate: 2020-06-30\n"+
"tags: dogs,doggo,pupper,floofer,woofters\ndescription: Whether you call them dogs\n---\nddddd"

var startPosition = yourText.search(tango)+tango.length;
var endPosition = yourText.slice(startPosition).search(tango)+startPosition;
yourText = yourText.slice(startPosition,endPosition);
Logger.log(yourText);
//at this point the variable yourText is isolated with proper captures.
// if you wanted to go further without Regex, you could make additional modifications...

yourText = "{" + yourText.replace(/: /g,':') +"}";
yourText = yourText.replace(/\n/g,'"\n"');
yourText = yourText.replace(/:/g,'" : "');


Logger.log(yourText);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM