简体   繁体   English

从 Markdown 中提取第一个 p 和 h1 标签内容

[英]Extract first p and h1 tag content from markdown

Suppose I have the following markdown content假设我有以下降价内容

# What is super?
Super is a keyword used to pass props to the upper classes.

Let's begin
...
..
etc..

For any blog, the title and description are really important.对于任何博客,标题和描述都非常重要。

For title, I would like to get the first # h1 tag and for description, I would like to get the first paragraph p tag.对于标题,我想获得第一个# h1 标签,而对于描述,我想获得第一个paragraph p 标签。

I can not use browser API because the code is running on NodeJs .我无法使用浏览器 API,因为代码在NodeJs上运行。

In the case of the above content, the title and description should be在上述内容的情况下,标题和描述应为

  • title - What is super?标题 - 什么是超级?
  • description - Super is a keyword used to pass props to the upper classes. description - Super 是用于将 props 传递给上层类的关键字。

How can I get the title and description?如何获得标题和描述?

Answer回答

const regex = {
  title: /^#\s+.+/,
  heading: /^#+\s+.+/,
  custom: /\$\$\s*\w+/,
  ol: /\d+\.\s+.*/,
  ul: /\*\s+.*/,
  task: /\*\s+\[.]\s+.*/,
  blockQuote: /\>.*/,
  table: /\|.*/,
  image: /\!\[.+\]\(.+\).*/,
  url: /\[.+\]\(.+\).*/,
  codeBlock: /\`{3}\w+.*/,
};

const isTitle = (str) => regex.title.test(str);
const isHeading = (str) => regex.heading.test(str);
const isCustom = (str) => regex.custom.test(str);
const isOl = (str) => regex.ol.test(str);
const isUl = (str) => regex.ul.test(str);
const isTask = (str) => regex.task.test(str);
const isBlockQuote = (str) => regex.blockQuote.test(str);
const isImage = (str) => regex.image.test(str);
const isUrl = (str) => regex.url.test(str);
const isCodeBlock = (str) => regex.codeBlock.test(str);

export function getMdTitle(md) {
  if (!md) return "";
  let tokens = md.split("\n");
  for (let i = 0; i < tokens.length; i++) {
    if (isTitle(tokens[i])) return tokens[i];
  }
  return "";
}

export function getMdDescription(md) {
  if (!md) return "";
  let tokens = md.split("\n");
  for (let i = 0; i < tokens.length; i++) {
    if (
      isHeading(tokens[i]) ||
      isCustom(tokens[i]) ||
      isOl(tokens[i]) ||
      isUl(tokens[i]) ||
      isTask(tokens[i]) ||
      isBlockQuote(tokens[i]) ||
      isImage(tokens[i]) ||
      isUrl(tokens[i]) ||
      isCodeBlock(tokens[i])
    )
      continue;

    return tokens[i];
  }
  return "";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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