Source

utils/markdown.utils.js

/**
 * Strips markdown formatting from text while preserving HTML/XML tags.
 * Used to clean AI assistant responses before displaying to users.
 * @param {string} text - The text containing markdown formatting
 * @returns {string} The text with markdown formatting removed
 */
export function stripMarkdown(text) {
    if (!text)
        return text;
    return (text
        // Remove code blocks (```...```)
        .replace(/```[\s\S]*?```/g, "")
        // Remove inline code (`...`)
        .replace(/`([^`]+)`/g, "$1")
        // Remove bold (**...** and __...__) and italic (*...* and _..._)
        .replace(/\*\*([^*]+)\*\*/g, "$1")
        .replace(/\*([^*]+)\*/g, "$1")
        .replace(/__([^_]+)__/g, "$1")
        .replace(/_([^_]+)_/g, "$1")
        // Remove strikethrough (~~...~~)
        .replace(/~~([^~]+)~~/g, "$1")
        // Remove headers (# ... ######)
        .replace(/^#{1,6}\s+/gm, "")
        // Remove images ![alt](url) - preserve URL
        .replace(/!\[([^\]]*)\]\(([^)]+)\)/g, "$2")
        // Remove links [text](url) - preserve URL
        .replace(/\[([^\]]*)\]\(([^)]+)\)/g, "$2")
        // Remove block quotes (>)
        .replace(/^[>\s]*>\s*/gm, "")
        // Remove unordered list markers (-, *, +)
        .replace(/^\s*[-*+]\s+/gm, "")
        // Remove ordered list markers (1., 2., etc)
        .replace(/^\s*\d+\.\s+/gm, "")
        // Collapse multiple newlines to max two
        .replace(/\n{3,}/g, "\n\n")
        .trim());
}