markdown提取摘要

2020-12-10  本文已影响0人  yanmingfei

说明

markdown中提取摘要,看似很简单,不过里面如果包含大面积的代码该如何处理?如何把一些不想要的东西过滤出去,把一些重要的信息变为摘要。
需要使用的库为 marked-ast

用法

var marked = require('marked-ast');
var ast = marked.parse('_This is **Markdown**_, he said.');
var html = marked.render(ast);

结果

[
  {
    "type": "paragraph",
    "text": [
      {
        "type": "em",
        "text": [
          "This is ",
          {
            "type": "strong",
            "text": [ "Markdown" ]
          }
        ]
      },
      ", he said."
    ]
  }
]

项目中的用法

  const markdownSummary = (content, len) => {
    if (content) {
      content = content.split('\n')
      const textArr = []
      for (let i = 0; i < content.length; i++) {
        const text = content[i].trim()
        if (text) {
          textArr.push(text)
        }
      }
      content = textArr.join('\n')
      const ast = marked.parse(content.trim())
      const str = parseMarkAst(ast).slice(0, len)
      return str
    }
    return ''
  }
  const parseMarkAst = (ast) => {
    let str = ''
    for (let i = 0; i < ast.length; i++) {
      const curAst = ast[i]
      if (curAst.type === 'heading' || curAst.type === 'paragraph' || curAst.type === 'strong' || curAst.type === 'em') {
        if (curAst.text.length === 1) {
          if (curAst.text !== '/n') {
            str += curAst.text[0].trim()
          }
        } else {
          for (let y = 0; y < curAst.text.length; y++) {
            const yAst = curAst.text[y]
            if (typeof yAst === 'object') {
              str += yAst.text[0].trim()
            } else {
              str += yAst.trim()
            }
          }
        }
      }
    }
    return str
  }
上一篇 下一篇

猜你喜欢

热点阅读