Search code examples
htmlslackslack-apislack-block-kit

Need a function for converting Slack Markdown to HTML


Is there an available package by which we can convert the slack block kit to HTML?

Or if someone has a function for the same, can you please help ?


Solution

  • If anyone is looking for something similar - here's the solution

    function slackMarkdownToHtml(markdown) {
      // Replace asterisks with bold tags
      let html = markdown.replace(/\*(.+?)\*/g, '<b>$1</b>');
    
      // Replace underscores with italic tags
      html = html.replace(/\_(.+?)\_/g, '<i>$1</i>');
    
      // Replace tildes with strike-through tags
      html = html.replace(/\~(.+?)\~/g, '<s>$1</s>');
    
      // Replace dashes with unordered list items
      html = html.replace(/- (.*)/g, '<li>$1</li>');
      html = html.replace(/\n-/g, '\n</ul><ul>-')
      html = '<ul>' + html + '</ul>';
    
      // Replace numbers with ordered list items
      html = html.replace(/[0-9]\. (.*)/g, '<li>$1</li>');
      html = html.replace(/\n[0-9]\./g, '\n</ol><ol>$&')
      html = '<ol>' + html + '</ol>';
    
      // Replace Slack's link syntax with anchor tags
      html = html.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>');
    
      return html;
    }
    

    Also, the reverse - HTML to Slack Markdown

    function htmlToSlackMarkdown(html) {
      // Replace newline characters with a line break
      let markdown = html.replace(/\n/g, '\n\n');
    
      // Replace bold tags with asterisks
      markdown = markdown.replace(/<b>/g, '*').replace(/<\/b>/g, '*');
    
      // Replace italic tags with underscores
      markdown = markdown.replace(/<i>/g, '_').replace(/<\/i>/g, '_');
    
      // Replace strike-through tags with tildes
      markdown = markdown.replace(/<s>/g, '~').replace(/<\/s>/g, '~');
    
      // Replace unordered list items with dashes
      markdown = markdown.replace(/<li>/g, '- ').replace(/<\/li>/g, '');
    
      // Replace ordered list items with numbers
      markdown = markdown.replace(/<ol>/g, '').replace(/<\/ol>/g, '');
      markdown = markdown.replace(/<li>/g, '1. ').replace(/<\/li>/g, '');
      markdown = markdown.replace(/\n1\./g, '\n2.');
      markdown = markdown.replace(/\n2\./g, '\n3.');
      markdown = markdown.replace(/\n3\./g, '\n4.');
      markdown = markdown.replace(/\n4\./g, '\n5.');
      markdown = markdown.replace(/\n5\./g, '\n6.');
      markdown = markdown.replace(/\n6\./g, '\n7.');
      markdown = markdown.replace(/\n7\./g, '\n8.');
      markdown = markdown.replace(/\n8\./g, '\n9.');
      markdown = markdown.replace(/\n9\./g, '\n10.');
    
      // Replace anchor tags with Slack's link syntax
      markdown = markdown.replace(/<a href="(.+?)">(.+?)<\/a>/g, '[$2]($1)');
    
      return markdown;
    }