64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
// 简单的Markdown渲染函数
|
||
export function renderMarkdown(content) {
|
||
if (!content) return '';
|
||
|
||
// 由于UniApp的rich-text组件支持HTML,我们将Markdown转换为HTML
|
||
// 这是一个简化版的Markdown解析器,仅支持基本语法
|
||
|
||
let html = content
|
||
// 转义HTML特殊字符
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
|
||
// 标题
|
||
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
|
||
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
|
||
.replace(/^### (.*$)/gm, '<h3>$1</h3>')
|
||
.replace(/^#### (.*$)/gm, '<h4>$1</h4>')
|
||
.replace(/^##### (.*$)/gm, '<h5>$1</h5>')
|
||
.replace(/^###### (.*$)/gm, '<h6>$1</h6>')
|
||
|
||
// 粗体和斜体
|
||
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
|
||
.replace(/\*(.*?)\*/g, '<em>$1</em>')
|
||
.replace(/__(.*?)__/g, '<strong>$1</strong>')
|
||
.replace(/_(.*?)_/g, '<em>$1</em>')
|
||
|
||
// 链接
|
||
.replace(/\[([^\]]+)\]$$([^)]+)$$/g, '<a href="$2">$1</a>')
|
||
|
||
// 图片
|
||
.replace(/!\[([^\]]+)\]$$([^)]+)$$/g, '<img src="$2" alt="$1">')
|
||
|
||
// 无序列表
|
||
.replace(/^\s*[-*+]\s+(.*$)/gm, '<li>$1</li>')
|
||
|
||
// 有序列表
|
||
.replace(/^\s*\d+\.\s+(.*$)/gm, '<li>$1</li>')
|
||
|
||
// 代码块
|
||
.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
|
||
|
||
// 行内代码
|
||
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
||
|
||
// 引用
|
||
.replace(/^\> (.*$)/gm, '<blockquote>$1</blockquote>')
|
||
|
||
// 段落
|
||
.replace(/\n\s*\n/g, '</p><p>')
|
||
|
||
// 换行
|
||
.replace(/\n/g, '<br>');
|
||
|
||
// 包装在段落标签中
|
||
html = '<p>' + html + '</p>';
|
||
|
||
// 修复列表
|
||
html = html.replace(/<li>.*?<\/li>/g, function(match) {
|
||
return '<ul>' + match + '</ul>';
|
||
});
|
||
|
||
return html;
|
||
} |