JS渲染MD公式换行问题

问题引出

本博客主要使用的是Markdown语言做笔记再渲染为静态的HTML文件。
但是在文章中,当进行公式渲染时发现不能使用\换行!
包括矩阵换行、公式换行…How terrible!

问题分析

首先使用的“marked”包对markdown文件进行渲染
那么很有可能就是因为在渲染的过程中,将 \ 直接当作转义符号了

就像是\n一样,把 \ 转义成 \ 了

解决方案1

经过狠狠地百度,找到了取消转义的方法,如下:

  1. 找到当前工程目录下的包安装目录

  2. 再找到其中的marked包

  3. 打开marked包中的库文件(主文件),路径如下:

    1
    nodes_modules/marked/lib/marked.js
  4. 使用搜索功能(当然你也可以肉眼hhh)寻找下面的代码

    建议查找关键字为“escape:”

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /**
    * Inline-Level Grammar
    */

    var inline = {
    escape: /^([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, //原本是escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/
    autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
    url: noop,
    tag: '^comment'
    + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
    + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section
    link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
    reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
    nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
    strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,
    em: /^_([^\s_])_(?!_)|^\*([^\s*<\[])\*(?!\*)|^_([^\s<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s<"][\s\S]*?[^\s\*])\*(?!\*|[^\spunctuation])|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,
    code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
    br: /^( {2,}|\\)\n(?!\s*$)/,
    del: noop,
    text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/
    };
  5. 删除转义符号组中的 // 元素,如上代码中注释的那样

    1
    escape: /^([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, //原本是escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]
  6. 问题解决啦!😎参见上一篇博客中的渲染效果

解决方案2

如果嫌弃上面一种方法太麻烦,当然也不是一种很稳定的方法
那么方案2是最简单的也是最好理解的

*把所有的 \ 打成 \\*

显然经过转义后4个\变成了2个\

版本说明

npm: ‘6.14.4’

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022-2023 RY.J
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信