Stripping frontmatter

I’m trying to read a page and get just the content of it in space lua, but I’ve struggled with matching newlines.

I’ve gotten this function which will correctly strip frontmatter with only a single line:

local function strip_frontmatter(text)
  return text:gsub("^%s*%-%-%-[\r\n]+.-[\r\n]+%-%-%-%s*", "")
end

but if I have multiple lines within the frontmatter it won’t work. I’ve tried combinations of %s, \r, \n, %w and . but I can’t find a pattern that’ll match newlines and non-newlines (e.g. [\r\n.] doesn’t work).

An example frontmatter that I have been unable to strip:

---
aliases:
  - Foo
  - Bar
public: true
---

tbc, things that I think ought to work based on online resources don’t work in SB, so I’d appreciate any help but please test it within SB specifically first.

there already is a functions to strip a text from its frontmatter API/index Documentation

index.extractFrontmatter(text, extractOptions)

To strip a frontmatter from a page:

function strip_frontmatter_page(page)
  local fm = index.extractFrontmatter(space.readPage(page),  {
    removeFrontMatterSection = true,
    removeTags = false
  })
  return fm.text
end

To strip frontmatter from a text

function strip_frontmatter_from_text(text)
  local fm = index.extractFrontmatter(text,  {
    removeFrontMatterSection = true,
    removeTags = false
  })
  return "Text without frontmatter: " .. fm.text .."\n\nAnd this is the frontmatter:" .. fm.frontmatter
end

here is a screenshot with the result for fm

1 Like