zoukankan      html  css  js  c++  java
  • 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 块预览了

  • 相关阅读:
    Spring Controller 获取请求参数的几种方法
    JSP ajax跨域问题 怎么处理 原因:CORS 头缺少 'Access-Control-Allow-Origin')。 ajax http 415
    仿微信滑动返回
    App重新启动
    NetWorkUtils
    ProgressWheel
    没有系统头部的dialog
    仿微信添加触摸图片阴影效果
    循环滚动TextView
    java 分割字符串后放入List中
  • 原文地址:https://www.cnblogs.com/raybiolee/p/6146209.html
Copyright © 2011-2022 走看看