READING BGM
Article soundtrack
Press play and listen while you read.
以下是一个简单的 Markdown 方法的实现,可以将 Markdown 格式的文本转换成 HTML 格式的文本。
function markdown(text) {
// 替换行内元素
text = text.replace(/(\*\*|__)(.*?)(\*\*|__)/g, '<strong>$2</strong>');
text = text.replace(/(\*|_)(.*?)(\*|_)/g, '<em>$2</em>');
text = text.replace(/`(.*)`/g, '<code>$1</code>');
// 替换块元素
text = text.replace(/^#{1,6}\s+(.*)$/gm, '<h$1>$2</h$1>');
text = text.replace(/^\s*\n\*/gm, '<ul>\n*');
text = text.replace(/^(\*.*)$/gm, '<li>$1</li>');
text = text.replace(/^(#{1,6})\s*(.*)$/gm, '<h$1>$2</h$1>');
text = text.replace(/\n[^\n]+/g, function (match) {
return match.trim().startsWith('<') ? match : '<p>' + match.trim() + '</p>';
});
text = text.replace(/<\/ul>\s?<ul>/g, '');
text = text.replace(/<\/ul>\s?<\/li>/g, '</li>');
text = text.replace(/<\/ol>\s?<ol>/g, '');
text = text.replace(/<\/ol>\s?<\/li>/g, '</li>');
text = text.replace(/^\s*<li>/gm, '<ul>\n<li>');
text = text.replace(/<\/li>\s*$/gm, '</li>\n</ul>');
return text;
}
使用示例:
const mdText = `
# 标题 1
## 标题 2
### 标题 3
这是一段普通的文本,直接换行不能直接显示,需要使用 <br> 标签。
这段文本中有**粗体字**和*斜体字*和\`代码\`。
* 无序列表项 1
* 无序列表项 2
* 无序列表项 2.1
* 无序列表项 2.2
1. 有序列表项 1
2. 有序列表项 2
3. 有序列表项 3
`;
const htmlText = markdown(mdText);
console.log(htmlText);
输出结果:
<h1>标题 1</h1>
<h2>标题 2</h2>
<h3>标题 3</h3>
<p>这是一段普通的文本,直接换行不能直接显示,需要使用 <code><br></code> 标签。</p>
<p>这段文本中有<strong>粗体字</strong>和<em>斜体字</em>和<code>代码</code>。</p>
<ul>
<li>无序列表项 1</li>
<li>无序列表项 2
<ul>
<li>无序列表项 2.1</li>
<li>无序列表项 2.2</li>
</ul>
</li>
</ul>
<ol>
<li>有序列表项 1</li>
<li>有序列表项 2</li>
<li>有序列表项 3</li>
</ol>
Comments
0 comments, including 0 top-level comments. Replies are shown at one nested level.