MCPcopy Create free account
hub / github.com/TeleBoxOrg/TeleBox_Plugins / markdownToHtml

Function markdownToHtml

outdated/gpt/gpt.ts:152–213  ·  view source on GitHub ↗
(text: string)

Source from the content-addressed store, hash-verified

150
151// 简单的Markdown到HTML转换函数
152function markdownToHtml(text: string): string {
153 // 首先对特殊HTML字符进行转义,但要保护已经存在的HTML标签
154 let result = text;
155
156 // 临时替换现有的HTML标签
157 const htmlTags: string[] = [];
158 let tagIndex = 0;
159 result = result.replace(/<\/?[a-zA-Z][^>]*>/g, (match) => {
160 htmlTags.push(match);
161 return `__HTML_TAG_${tagIndex++}__`;
162 });
163
164 // 转义其他HTML字符
165 result = result
166 .replace(/&/g, "&amp;")
167 .replace(/</g, "&lt;")
168 .replace(/>/g, "&gt;");
169
170 // 恢复HTML标签
171 htmlTags.forEach((tag, index) => {
172 result = result.replace(`__HTML_TAG_${index}__`, tag);
173 });
174
175 // 应用markdown转换
176 result = result
177 // 代码块 (```) - 先处理,避免内部内容被其他规则影响
178 .replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
179 const escapedCode = code
180 .replace(/&lt;/g, "<")
181 .replace(/&gt;/g, ">")
182 .replace(/&amp;/g, "&");
183 return `<pre><code>${htmlEscape(escapedCode)}</code></pre>`;
184 })
185 // 行内代码 (`)
186 .replace(/`([^`]+)`/g, (match, code) => {
187 const escapedCode = code
188 .replace(/&lt;/g, "<")
189 .replace(/&gt;/g, ">")
190 .replace(/&amp;/g, "&");
191 return `<code>${htmlEscape(escapedCode)}</code>`;
192 })
193 // 粗体 (**)
194 .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
195 // 斜体 (*) - 简化版本,避免与粗体冲突
196 .replace(/\*([^*\n]+)\*/g, "<i>$1</i>")
197 // 粗体 (__)
198 .replace(/__([^_]+)__/g, "<b>$1</b>")
199 // 斜体 (_) - 简化版本,避免与粗体冲突
200 .replace(/_([^_\n]+)_/g, "<i>$1</i>")
201 // 删除线 (~~)
202 .replace(/~~([^~]+)~~/g, "<s>$1</s>")
203 // 链接 [text](url)
204 .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
205 // 标题 (# ## ###)
206 .replace(/^### (.+)$/gm, "<b>$1</b>")
207 .replace(/^## (.+)$/gm, "<b>$1</b>")
208 .replace(/^# (.+)$/gm, "<b>$1</b>")
209 // 引用 (>)

Callers 1

formatResponseFunction · 0.70

Calls 1

htmlEscapeFunction · 0.70

Tested by

no test coverage detected