George
George

Reputation: 7317

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?

Upvotes: 0

Views: 90

Answers (1)

Danila Shutov
Danila Shutov

Reputation: 502

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

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

Upvotes: 1

Related Questions