gy-app-shop/pages/fun/markdown.js

64 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 简单的Markdown渲染函数
export function renderMarkdown(content) {
if (!content) return '';
// 由于UniApp的rich-text组件支持HTML我们将Markdown转换为HTML
// 这是一个简化版的Markdown解析器仅支持基本语法
let html = content
// 转义HTML特殊字符
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// 标题
.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;
}