postText

tcmts.site.postText · #nrqlgjgi · function · runs anywhere

A post's title (its # heading) and first paragraph, as plain text: what a record of it says it is.

import { markdown } from "#codebase/tcmts/content";

export function postText(md: string): { title: string; description: string } {
  const plain = (s: string) =>
    markdown(s)
      .replace(/<[^>]+>/g, "")
      .replace(
        /&(lt|gt|quot|#39|amp);/g,
        (_, e: string) => ({ lt: "<", gt: ">", quot: '"', "#39": "'", amp: "&" })[e]!,
      )
      .replace(/\s+/g, " ")
      .trim();
  const title = plain(/^#\s+(.+)$/m.exec(md)?.[1] ?? "");
  const first =
    md
      .replace(/^#\s+.*$/m, "")
      .split(/\n\s*\n/)
      .map((p) => p.trim())
      .find((p) => p && !/^(#|```|~~~|[-*+] |\d+\. |>|\||<)/.test(p)) ?? "";
  return { title, description: plain(first) };
}

uses

used by