MCPcopy Create free account
hub / github.com/CatMuse/HiNote / removeHighlightFormat

Method removeHighlightFormat

src/utils/HighlightRegexUtils.ts:20–81  ·  view source on GitHub ↗

* 移除文本中的高亮格式,保留纯文本 * @param content 文件内容 * @param highlightText 要移除格式的高亮文本 * @param customRegex 自定义正则表达式(可选) * @returns 移除格式后的内容

(
        content: string,
        highlightText: string,
        customRegex?: string
    )

Source from the content-addressed store, hash-verified

18 * @returns 移除格式后的内容
19 */
20 static removeHighlightFormat(
21 content: string,
22 highlightText: string,
23 customRegex?: string
24 ): string {
25 const escapedText = this.escapeRegExp(highlightText);
26 let newContent = content;
27 let replaced = false;
28
29 // 1. 尝试标准的 Markdown 高亮格式 ==text==
30 const markdownHighlightRegex = new RegExp(`==\\s*(${escapedText})\\s*==`, 'g');
31 const mdResult = newContent.replace(markdownHighlightRegex, highlightText);
32 if (mdResult !== newContent) {
33 newContent = mdResult;
34 replaced = true;
35 }
36
37 // 2. 尝试 <mark>text</mark> 格式
38 if (!replaced) {
39 const markTagRegex = new RegExp(`<mark[^>]*>(${escapedText})</mark>`, 'g');
40 const markResult = newContent.replace(markTagRegex, highlightText);
41 if (markResult !== newContent) {
42 newContent = markResult;
43 replaced = true;
44 }
45 }
46
47 // 3. 尝试 <span>text</span> 格式
48 if (!replaced) {
49 const spanTagRegex = new RegExp(`<span[^>]*>(${escapedText})</span>`, 'g');
50 const spanResult = newContent.replace(spanTagRegex, highlightText);
51 if (spanResult !== newContent) {
52 newContent = spanResult;
53 replaced = true;
54 }
55 }
56
57 // 4. 如果提供了自定义正则表达式,尝试使用
58 if (!replaced && customRegex) {
59 try {
60 const customRegexObj = new RegExp(customRegex, 'g');
61 const customResult = newContent.replace(customRegexObj, (match, ...groups) => {
62 // 检查匹配的文本是否包含我们要查找的高亮文本
63 for (const group of groups) {
64 if (typeof group === 'string' && group.includes(highlightText)) {
65 return highlightText;
66 }
67 }
68 return match; // 如果没有找到匹配的组,保持原样
69 });
70
71 if (customResult !== newContent) {
72 newContent = customResult;
73 replaced = true;
74 }
75 } catch (error) {
76 console.error('自定义正则表达式错误:', error);
77 }

Callers 2

Calls 2

escapeRegExpMethod · 0.95
replaceMethod · 0.80

Tested by

no test coverage detected