Strip HTML tags into readable text. Lightweight; doesn't preserve structure.
(html: string)
| 80 | |
| 81 | /** Strip HTML tags into readable text. Lightweight; doesn't preserve structure. */ |
| 82 | function htmlToText(html: string): string { |
| 83 | // Remove script/style first so their contents don't leak through |
| 84 | html = html.replace(/<script[\s\S]*?<\/script>/gi, ''); |
| 85 | html = html.replace(/<style[\s\S]*?<\/style>/gi, ''); |
| 86 | html = html.replace(/<!--[\s\S]*?-->/g, ''); |
| 87 | // Convert block elements to newlines for readability |
| 88 | html = html.replace(/<\/(p|div|h[1-6]|li|tr|br)[^>]*>/gi, '\n'); |
| 89 | html = html.replace(/<br[^>]*>/gi, '\n'); |
| 90 | // Strip all remaining tags |
| 91 | html = html.replace(/<[^>]+>/g, ''); |
| 92 | // HTML entities (just the common ones) |
| 93 | html = html |
| 94 | .replace(/ /g, ' ') |
| 95 | .replace(/&/g, '&') |
| 96 | .replace(/</g, '<') |
| 97 | .replace(/>/g, '>') |
| 98 | .replace(/"/g, '"') |
| 99 | .replace(/'/g, "'") |
| 100 | .replace(/'/g, "'"); |
| 101 | // Collapse whitespace |
| 102 | html = html.replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n'); |
| 103 | return html.trim(); |
| 104 | } |
| 105 | |
| 106 | /** Best-effort HTML→markdown. Captures headings, links, lists, code, paragraphs. */ |
| 107 | function htmlToMarkdown(html: string): string { |