js: markdown-it: Markdown解析器

文档:

安装依赖

npm i -S markdown-it markdown-it-for-inline

代码示例

1、默认default

linkify: false


var md = require("markdown-it")()

const text = "http://www.baidu.com";
var result = md.render(text);
console.log(result);

输出

<p>http://www.baidu.com</p>

2、自动识别url

linkify: true


var md = require("markdown-it")({ linkify: true })

const text = "http://www.baidu.com";
var result = md.render(text);
console.log(result);

输出

<p><a href="http://www.baidu.com">http://www.baidu.com</a></p>

3、自动识别url 并设置新窗口打开

linkify: true && target=_blank

var iterator = require("markdown-it-for-inline");

var md = require("markdown-it")({ linkify: true }).use(
  iterator,
  "url_new_win",
  "link_open",
  function(tokens, idx) {
    var aIndex = tokens[idx].attrIndex("target");

    if (aIndex < 0) {
      tokens[idx].attrPush(["target", "_blank"]);
    } else {
      tokens[idx].attrs[aIndex][1] = "_blank";
    }
  }
);

const text = "http://www.baidu.com";
var result = md.render(text);
console.log(result);

输出

<p><a href="http://www.baidu.com" target="_blank">http://www.baidu.com</a></p>