-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrip.ts
More file actions
69 lines (49 loc) · 2.47 KB
/
strip.ts
File metadata and controls
69 lines (49 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Strips Markdown formatting from text, preserving readable plaintext.
* Designed for messaging channels that don't render Markdown (iMessage, SMS, Signal, etc.).
*/
export function stripMarkdown(text: string): string {
if (!text) return text;
let result = text;
// Fenced code blocks: remove ``` markers and optional language tag, keep content
result = result.replace(/^```[\w-]*\n?([\s\S]*?)```$/gm, '$1');
// Inline code: remove backticks, keep content
result = result.replace(/`([^`]+)`/g, '$1');
// Images:  → alt
result = result.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1');
// Links: [text](url) → text (handles URLs with balanced parentheses)
result = result.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
// Reference-style links: [text][ref] → text
result = result.replace(/\[([^\]]+)\]\[[^\]]*\]/g, '$1');
// Reference definitions: [ref]: url → remove entirely
result = result.replace(/^\[[^\]]+\]:\s+.*$/gm, '');
// Bold+italic: ***text*** or ___text___
result = result.replace(/\*{3}(.+?)\*{3}/g, '$1');
result = result.replace(/_{3}(.+?)_{3}/g, '$1');
// Bold: **text** or __text__
result = result.replace(/\*{2}(.+?)\*{2}/g, '$1');
result = result.replace(/_{2}(.+?)_{2}/g, '$1');
// Italic: *text* or _text_ (careful not to match mid-word underscores like snake_case_vars)
result = result.replace(/(?<![\\*\w])\*([^*\n]+?)\*(?![*\w])/g, '$1');
result = result.replace(/(?<![_\\\w])_([^_\n]+?)_(?![_\w])/g, '$1');
// Strikethrough: ~~text~~
result = result.replace(/~~(.+?)~~/g, '$1');
// Headers: # text → text (1-6 levels)
result = result.replace(/^#{1,6}\s+/gm, '');
// Blockquotes: > text → text (supports nested >>)
result = result.replace(/^(?:>\s?)+/gm, '');
// Horizontal rules: ---, ***, ___ (with optional spaces)
result = result.replace(/^[\t ]*[-*_]{3,}[\t ]*$/gm, '');
// Unordered list markers: - item, * item, + item → item (preserves indentation level)
result = result.replace(/^([\t ]*)[-*+]\s+/gm, '$1');
// Task list markers: - [ ] or - [x] → remove checkbox
result = result.replace(/^([\t ]*)\[[ xX]\]\s+/gm, '$1');
// HTML comments
result = result.replace(/<!--[\s\S]*?-->/g, '');
// Escaped markdown chars: \* \_ \` \# etc. → remove backslash
result = result.replace(/\\([\\`*_{}[\]()#+\-.!~>|$])/g, '$1');
// Clean up multiple consecutive blank lines
result = result.replace(/\n{3,}/g, '\n\n');
// Trim leading/trailing whitespace
return result.trim();
}