วิธีลบ Markdown จาก AI Response ใน n8n ☕

สวัสดีครับ! วันนี้ผมจะมาแชร์วิธีการจัดการกับ AI Response ที่มี Markdown ใน n8n ซึ่งเป็นปัญหาที่เจอบ่อยมากเวลาใช้ AI nodes ครับ 😅

🎯 ปัญหาที่เจอบ่อย

เวลา AI ตอบกลับมา มักจะมี:

  • Bold text **text**
  • Italic text *text*
  • Headers # ## ###
  • Code blocks ```code```
  • Lists - item หรือ 1. item

💡 วิธีแก้ไข

วิธีที่แก้ใช้ JavaScript ใน Code Node

// ฟังก์ชันสำหรับลบ Markdown
function removeMarkdown(text) {
  if (!text || typeof text !== 'string') {
    return text;
  }
  
  return text
    // ลบ Headers (# ## ### #### ##### ######)
    .replace(/^#{1,6}\s+/gm, '')
    
    // ลบ Bold (**text** และ __text__)
    .replace(/\*\*(.*?)\*\*/g, '$1')
    .replace(/__(.*?)__/g, '$1')
    
    // ลบ Italic (*text* และ _text_)
    .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '$1')
    .replace(/(?<!_)_([^_]+)_(?!_)/g, '$1')
    
    // ลบ Strikethrough (~~text~~)
    .replace(/~~(.*?)~~/g, '$1')
    
    // ลบ Code blocks (```code```)
    .replace(/```[\s\S]*?```/g, '')
    
    // ลบ Inline code (`code`)
    .replace(/`([^`]+)`/g, '$1')
    
    // ลบ Links [text](url)
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    
    // ลบ Images ![alt](url)
    .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
    
    // ลบ Blockquotes (> text)
    .replace(/^>\s+/gm, '')
    
    // ลบ Horizontal rules (--- หรือ ***)
    .replace(/^[-*_]{3,}$/gm, '')
    
    // ลบ Unordered lists (- item, * item, + item)
    .replace(/^[-*+]\s+/gm, '')
    
    // ลบ Ordered lists (1. item)
    .replace(/^\d+\.\s+/gm, '')
    
    // ลบ Tables (| col1 | col2 |)
    .replace(/\|.*\|/g, '')
    .replace(/^\s*[-:]+[-:\s]*$/gm, '')
    
    // ลบบรรทัดว่างเกิน
    .replace(/\n\s*\n\s*\n/g, '\n\n')
    
    // ตัดช่องว่างหน้าหลัง
    .trim();
}

// รับข้อมูลจาก AI Agent
const aiResponse = $input.item.json.output || $input.item.json.response || $input.item.json.text;

// ทำความสะอาด Markdown
const cleanText = removeMarkdown(aiResponse);

// ส่งผลลัพธ์
return {
  json: {
    originalText: aiResponse,
    cleanText: cleanText,
    markdown_removed: true,
    processing_time: new Date().toISOString()
  }
};

🔍 การแก้ไขปัญหาที่พบบ่อย

ปัญหา: Regex ไม่ทำงาน แก้ไข: ตรวจสอบ escape characters ใน string

ปัญหา: ลบข้อความหายไป แก้ไข: ทดสอบ regex ทีละตัวใน console ก่อน

💡 เคล็ดลับจากผม

  • Test Regex ใน regex101.com ก่อนใช้จริง
  • เก็บ backup ของข้อความต้นฉบับไว้เสมอ
  • ใช้ Try-Catch ใน Code Node เพื่อป้องกัน error
  • แบ่ง process เป็นขั้นตอนย่อยๆ เพื่อ debug ง่าย

n8n #automation #markdown #textprocessing #DataEspresso ☕

Short Link: https://data-espresso.com/u212

Leave a Comment

สอบถามข้อมูล
Scroll to Top