To implement this method, you can replace any empty line with two or more spaces with newlines and a specific token. Then, when posting in markdown format, substitute paragraphs with that token to create line breaks.
// 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);
// Condense multiple empty line paragraphs 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("");
});
// Replace basic newlines
mdHtml = mdHtml.replace(/<p>EMPTY_LINE<\/p>/g, "<br>");
This method identifies every new line with only a few spaces or more. By utilizing positive lookahead, it is able to correctly initiate the next replacement until two successive lines without spaces are encountered.
Subsequently, during markdown parsing, these lines will turn into paragraphs containing solely the token "EMPTY_LINE". Subsequently, these can be switched out for line breaks within the rawHtml text.
Additionally, the function used for replacement will combine all line break paragraphs if both upper and lower paragraphs exist.
In practical terms, its usage would look like this:
A sentence with trailing spaces
and blank lines interspersed with spaces will merge into a multi-line paragraph.
A sentence without trailing spaces
and lines with spaces between them will form two distinct paragraphs with additional space.
The outcome will resemble the following after implementation:
<p>
A sentence with trailing spaces<br>
<br>
<br>
and blank lines interspersed with spaces will merge into a multi-line paragraph.
</p>
<p>A sentence without trailing spaces</p>
<br>
<br>
<p>And lines with spaces between them will result in two paragraphs with extra spacing.</p>