• markdown-js 添加表格,代码块 parse


    简介

    markdown-js 是将 markdown转换成 HTML 的 JavaScript 库,我再网站中使用它来预览 markdown ,但是发现它对 代码块表格 是不转换的。这么鸡肋的地方居然没有修复,所以需要,在不改变它的 js 文件的情况下,把 代码块表格 的预览加上去。

    • jQuery 3.x

    代码

    ////////////////////////////
    // code 外加 pre
    // 代码中间有空行无法正确 parse
    ///////////////////////////
    var rst = markdown.toHTML($('#new-post-content').val()), mcode = new RegExp(/<code>([a-zA-Z]+)?([^<>]*(
    ?
    |
    ))+</code>/,'gu'), curM = 1;
    while(curM !== null){
    	// mcode不加g选项,会陷入死循环
    	curM = mcode.exec(rst);
    	if(curM !== null){
    		var lang = curM[1] === undefined ? 'text' : curM[1], cont = curM[2];
    		rst = rst.replace(curM[0], '<pre><code class="'+lang+'">'+cont+'</code></pre>');
    	}
    }
    // 中间有空行的
    var bcode = new RegExp(/<p><code></code>`([a-zA-Z]+)?([^]*)<code></code>`</p>/,'gu'), curB = 1;
    while(curB !== null){
    	curB = bcode.exec(rst);
    	if(curB !== null){
    		var lang = curB[1] === undefined ? 'text' : curB[1], cont = curB[2], cont = cont.replace(/</?p>/g, '').replace(/^(
    ?
    |
    )/, '');
    		rst = rst.replace(curB[0], '<pre><code class="'+lang+'">'+cont+'</code></pre>');
    	}
    }
    ///////////////
    // 解析 table
    ///////////////
    var tcode = new RegExp(/(|(?:[^
    |]+|)+)(?:
    ?
    |
    )|(?:[-—]+|)+((?:(?:
    ?
    |
    )(?:|(?:[^
    
    |]+|)+))+)/,'gu'), curT = 1;
    while(curT !== null){
    	curT=tcode.exec(rst);
    	if(curT !== null){
    		console.log(curT[2].split(/
    ?
    |
    /));
    		var rows = curT[2].split(/
    ?
    |
    /).filter(function(a){return a.length === 0 ? false : true;}), rowtrs = '<table><thead><tr><td>'+curT[1].split('|').slice(1,-1).join('</td><td>')+'</td></tr></thead><tbody>';
    		console.log(rows);
    		for(var i in rows){
    			rowtrs += '<tr><td>'+rows[i].split('|').slice(1,-1).join("</td><td>")+'</td></tr>';
    		}
    		rowtrs += '</tbody></table>';
    		rst = rst.replace(curT[0], rowtrs);
    	}
    };
    $('#output').html(rst);
    

    结果

    现在可以简单的对表格和多行的 code 块预览了

  • 相关阅读:
    博客备份小工具3
    博客转发小工具1
    04-属性选择器
    05-伪类选择器
    03-高级选择器
    02-css的选择器
    01-css的引入方式
    函数进阶-(命名空间、作用域、函数嵌套、作用域链、函数名本质、闭包)
    函数基础-(引子、定义函数、调用函数、函数返回值、函数参数)
    Python之路【第08章】:Python函数
  • 原文地址:https://www.cnblogs.com/raybiolee/p/6146209.html
Copyright © 2020-2023  润新知