web/src/utils/parse-markdown.ts

41 lines · 1384 bytes

 1import { marked } from 'marked';
 2
 3export const parseMarkdown = (text: string | undefined): string => {
 4  if (!text) return '';
 5
 6  // Custom renderer
 7  const renderer = new marked.Renderer();
 8
 9  // Override function to handle headings
10  renderer.heading = (text, level) => {
11    const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
12    return `<h${level} id="${escapedText}">${text}</h${level}>`;
13  };
14
15  // Override function to handle links
16  renderer.link = (href, title, text) => {
17    if (href.startsWith('/')) {
18      href = `https://github.com/Lissy93/personal-security-checklist/blob/old-version/${href}`;
19    }
20    title = title ? `title="${title}"` : '';
21    return `<a href="${href}" ${title} target="_blank" rel="noopener noreferrer">${text}</a>`;
22  };
23
24  // Sanitize the input to remove <script> tags
25  const sanitizeHtml = (html: string): string => {
26    return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
27  };
28
29  // Configure marked with the custom renderer
30  marked.use({ renderer });
31
32  // Parse the markdown, then sanitize the HTML to remove <script> tags
33  const rawHtml = marked.parse(text, { async: false}) as string;
34  const sanitizedHtml = sanitizeHtml(rawHtml);
35
36  return sanitizedHtml;
37};
38
39export const formatLink = (link: string) => {
40  return (link || '').replace(/^(https?:\/\/)?(www\.)?/, '').replace(/\/+$/, '');
41};