From a817acfb288bc025dcbe8ba7507b6a2adf6e0a55 Mon Sep 17 00:00:00 2001 From: hebo Date: Tue, 2 Sep 2025 22:05:54 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=89=E8=AF=BE=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/richText.ts | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/utils/richText.ts diff --git a/src/utils/richText.ts b/src/utils/richText.ts new file mode 100644 index 0000000..1046804 --- /dev/null +++ b/src/utils/richText.ts @@ -0,0 +1,99 @@ +/** + * 富文本处理工具函数 + */ + +/** + * 转换HTML实体字符为普通字符 + * @param html 包含HTML实体字符的字符串 + * @returns 转换后的字符串 + */ +export function decodeHtmlEntities(html: string): string { + if (!html) return ""; + + return html + // 转换HTML实体字符 + .replace(/“/g, '"') + .replace(/”/g, '"') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/'/g, "'") + .replace(///g, '/') + .replace(/`/g, '`') + .replace(/=/g, '=') + .replace(/+/g, '+') + .replace(/#/g, '#') + .replace(/$/g, '$') + .replace(/%/g, '%') + .replace(/&/g, '&') + .replace(/(/g, '(') + .replace(/)/g, ')') + .replace(/*/g, '*') + .replace(/,/g, ',') + .replace(/-/g, '-') + .replace(/./g, '.') + .replace(/;/g, ';') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/@/g, '@') + .replace(/[/g, '[') + .replace(/\/g, '\\') + .replace(/]/g, ']') + .replace(/^/g, '^') + .replace(/_/g, '_') + .replace(/{/g, '{') + .replace(/|/g, '|') + .replace(/}/g, '}') + .replace(/~/g, '~'); +} + +/** + * 提取纯文本内容(去除HTML标签) + * @param html 包含HTML标签的字符串 + * @returns 纯文本内容 + */ +export function extractPlainText(html: string): string { + if (!html) return ""; + + // 先解码HTML实体字符 + const decoded = decodeHtmlEntities(html); + + // 去除HTML标签 + return decoded.replace(/<[^>]*>/g, '').trim(); +} + +/** + * 格式化富文本内容用于显示 + * @param html 原始HTML内容 + * @returns 格式化后的HTML内容 + */ +export function formatRichTextForDisplay(html: string): string { + if (!html) return ""; + + // 解码HTML实体字符 + let formatted = decodeHtmlEntities(html); + + // 确保段落之间有适当的间距 + formatted = formatted.replace(/<\/p>\s*

/g, '

'); + + // 确保列表项格式正确 + formatted = formatted.replace(/<\/li>\s*

  • /g, '
  • '); + + return formatted; +} + +/** + * 获取富文本内容的摘要(前100个字符) + * @param html 富文本内容 + * @param maxLength 最大长度,默认100 + * @returns 摘要文本 + */ +export function getRichTextSummary(html: string, maxLength: number = 100): string { + const plainText = extractPlainText(html); + if (plainText.length <= maxLength) return plainText; + + return plainText.substring(0, maxLength) + '...'; +}