This commit is contained in:
ywyonui 2025-09-02 22:15:40 +08:00
commit 4c22f0dbee

99
src/utils/richText.ts Normal file
View File

@ -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(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&#x27;/g, "'")
.replace(/&#x2F;/g, '/')
.replace(/&#x60;/g, '`')
.replace(/&#x3D;/g, '=')
.replace(/&#x2B;/g, '+')
.replace(/&#x23;/g, '#')
.replace(/&#x24;/g, '$')
.replace(/&#x25;/g, '%')
.replace(/&#x26;/g, '&')
.replace(/&#x28;/g, '(')
.replace(/&#x29;/g, ')')
.replace(/&#x2A;/g, '*')
.replace(/&#x2C;/g, ',')
.replace(/&#x2D;/g, '-')
.replace(/&#x2E;/g, '.')
.replace(/&#x3B;/g, ';')
.replace(/&#x3C;/g, '<')
.replace(/&#x3E;/g, '>')
.replace(/&#x40;/g, '@')
.replace(/&#x5B;/g, '[')
.replace(/&#x5C;/g, '\\')
.replace(/&#x5D;/g, ']')
.replace(/&#x5E;/g, '^')
.replace(/&#x5F;/g, '_')
.replace(/&#x7B;/g, '{')
.replace(/&#x7C;/g, '|')
.replace(/&#x7D;/g, '}')
.replace(/&#x7E;/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*<p>/g, '</p><p>');
// 确保列表项格式正确
formatted = formatted.replace(/<\/li>\s*<li>/g, '</li><li>');
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) + '...';
}