From 97efa6ccdd06a4b62c78546e85c36609859334bc Mon Sep 17 00:00:00 2001 From: tianyaxiang Date: Tue, 4 Feb 2025 09:34:18 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E4=BB=A3=E7=A0=81,=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E7=BB=9F=E8=AE=A1=E5=AD=97=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/editor/hooks/useWordStats.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/components/editor/hooks/useWordStats.ts b/src/components/editor/hooks/useWordStats.ts index 59308c4..32b131b 100644 --- a/src/components/editor/hooks/useWordStats.ts +++ b/src/components/editor/hooks/useWordStats.ts @@ -1,4 +1,5 @@ import { useState, useEffect } from 'react' +import { convertToWechat } from '@/lib/markdown' // 计算阅读时间(假设每分钟阅读300字) const calculateReadingTime = (text: string): string => { @@ -13,12 +14,25 @@ const calculateWordCount = (text: string): string => { return count.toLocaleString() } +// 从 HTML 中提取纯文本 +const extractTextFromHtml = (html: string): string => { + // 创建一个临时的 div 元素 + const tempDiv = document.createElement('div') + tempDiv.innerHTML = html + // 获取纯文本内容 + return tempDiv.textContent || '' +} + export const useWordStats = (content: string) => { const [wordCount, setWordCount] = useState('0') const [readingTime, setReadingTime] = useState('1 分钟') useEffect(() => { - const plainText = content.replace(/<[^>]+>/g, '') + // 首先将 Markdown 转换为 HTML + const html = convertToWechat(content, {}) + // 从 HTML 中提取纯文本 + const plainText = extractTextFromHtml(html) + // 计算字数和阅读时间 setWordCount(calculateWordCount(plainText)) setReadingTime(calculateReadingTime(plainText)) }, [content])