Markdown与html互转markdown.js_showdown.js_marked.js_turndown.js

Markdown与html互转markdown.js_showdown.js_marked.js_turndown.js

本文主要介绍markdown与html互转,使用markdown.js,showdown.js,marked.js和turndown.js。
  1. Markdown.js markdown转html
  2. showdown.js markdown转html
  3. marked.js markdown转html
  4. turndown.js html转markdown

Markdown转html之markdown.js

<script src="https://cdn.bootcdn.net/ajax/libs/markdown.js/0.5.0/markdown.min.js"></script>
<script>
    let html = markdown.toHTML("####Hello https://www.fujuhao.com");
    console.log(html); // <h4>Hello https://www.fujuhao.com</h4>
</script>

Markdown转html之showdown.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.6.4/showdown.min.js"></script>
<script>
    let converter = new showdown.Converter();
    let html = converter.makeHtml("####Hello https://www.fujuhao.com");
    console.log(html); // <h4 id="hellohttpswwwfujuhaocom">Hello https://www.fujuhao.com</h4>
</script>

Markdown转html之marked.js 推荐

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
    let html = marked.parse("####Hello https://www.fujuhao.com");
    console.log(html); // <p>####Hello <a href="https://www.fujuhao.com">https://www.fujuhao.com</a></p>
</script>

使用Marked.js 对a标签和img标签的解析规则重写,用于自定义标签属性

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
    var renderer = new marked.Renderer();
    renderer.link = function(href,title,text){
        let rel = 'nofollow';
        // 本站的链接
        if(href.indexOf('https://www.fujuhao.com') >= 0){
            rel = '';
        }
        return `<a href="${href}" title="${title}" rel="${rel}" target="_blank">${text}</a>`;
    }
    renderer.image = function(href,title,text){
        let size = title;
        return `<img src="${href}" title="${title}" alt="${text}" data-size="${size}"/>`;
    }
    marked.use({
        renderer:renderer,
        xhtml: true,
    });
    let html = marked.parse("####Hello https://www.fujuhao.com");
    console.log(html); // <p>####Hello <a href="https://www.fujuhao.com" title="undefined" rel="" target="_blank">https://www.fujuhao.com</a></p>
</script>

使用turndown.js 将Html 转 Markdown语法

<script src="https://unpkg.com/turndown/dist/turndown.js"></script>
<script>
    let html = '<p>####Hello <a href="https://www.fujuhao.com" title="undefined" rel="" target="_blank">https://www.fujuhao.com</a></p>';
    // html转markdown配置
       const turndownService = new TurndownService({
        headingStyle: 'atx',
        bulletListMarker: '*',
        codeBlockStyle: 'fenced',
        emDelimiter: '*'
    });
    // 转换时要保留的标签
    turndownService.keep(['video', 'audio']);
    // 转换时需要移除的标签
    // turndownService.remove('xxx');
    var markdown = turndownService.turndown(html);
       console.log('markdown:',markdown); // ####Hello [https://www.fujuhao.com](https://www.fujuhao.com "undefined")
</script>
Loading...