破解此问题的一种方法是将任何空行替换为两个或多个空格,并带有一些换行符和一个标记。然后发布降价,仅用该标记替换段落以换行。
// replace empty lines with "EMPTY_LINE"
rawMdText = rawMdText.replace(/\n +(?=\n)/g, "\n\nEMPTY_LINE\n");
// put <br> at the end of any other line with two spaces
rawMdText = rawMdText.replace(/ +\n/, "<br>\n");
// parse
let rawHtml = markdownParse(rawMdText);
// for any paragraphs that end with a newline (injected above)
// and are followed by multiple empty lines leading to
// another paragraph, condense them into one paragraph
mdHtml = mdHtml.replace(/(<br>\s*<\/p>\s*)(<p>EMPTY_LINE<\/p>\s*)+(<p>)/g, (match) => {
return match.match(/EMPTY_LINE/g).map(() => "<br>").join("");
});
// for basic newlines, just replace them
mdHtml = mdHtml.replace(/<p>EMPTY_LINE<\/p>/g, "<br>");
这样做的目的是找到每个新行,只有几个空格+。它使用前瞻,以便它从正确的位置开始进行下一次替换,如果没有它,它将连续两行中断。
然后 Markdown 会将这些行解析为只包含标记“EMPTY_LINE”的段落。因此,您可以浏览 rawHtml 并用换行符替换它们。
作为奖励,如果存在,替换功能会将所有换行段落压缩为上段和下段。
实际上,您可以像这样使用它:
A line with spaces at end
and empty lines with spaces in between will condense into a multi-line paragraph.
A line with no spaces at end
and lines with spaces in between will be two paragraphs with extra lines between.
输出将是这样的:
<p>
A line with spaces at end<br>
<br>
<br>
and empty lines with spaces in between will condense into a multi-line paragraph.
</p>
<p>A line with no spaces at end</p>
<br>
<br>
<p>and lines with spaces in between will be two paragraphs with extra lines between.</p>