George February 2016

Grabbing only the YAML text from a file in JS

Suppose I have a file that has random text mixed with yaml text. The yaml text is always between a --- and a ....

Goal: My goal is to take a string (taken from such a file):

---
some: "yaml"
some: "more yaml"
...

Some random text that's not yaml.

---
more: "yaml"
...

And output a string that contains only the yaml parts (including the --- and ... delimiters):

---
some: "yaml"
some: "more yaml"
...    
---
more: "yaml"
...

How does one do this?

Answers


Danila Shutov February 2016

This can be easily done with String.prototype.match + Array.prototype.join:

function extractYaml(string) {
    return string.match(/(---(.|\n)*?\.\.\.\n)/g).join('');
}

Post Status

Asked in February 2016
Viewed 2,285 times
Voted 9
Answered 1 times

Search




Leave an answer