Markdown to HTML Converter JavaScript

👤 Sharing: AI
```javascript
function markdownToHTML(markdownText) {
  let html = "";
  const lines = markdownText.split("\n");

  for (const line of lines) {
    if (line.startsWith("# ")) {
      // Heading 1
      html += `<h1>${line.substring(2)}</h1>`;
    } else if (line.startsWith("## ")) {
      // Heading 2
      html += `<h2>${line.substring(3)}</h2>`;
    } else if (line.startsWith("### ")) {
      // Heading 3
      html += `<h3>${line.substring(4)}</h3>`;
    } else if (line.startsWith("- ")) {
      // Unordered list item
      html += `<li>${line.substring(2)}</li>`;
    } else if (line.startsWith("* ")) {
      // Unordered list item
      html += `<li>${line.substring(2)}</li>`;
    } else if (line.match(/^\d+\. /)) {
      // Ordered list item
      const match = line.match(/^(\d+)\. (.*)/);
      if (match) {
        html += `<li>${match[2]}</li>`;
      }
    } else if (line === "") {
      // Empty line (paragraph break)
      html += "<br>";
    } else {
      // Paragraph
      html += `<p>${line}</p>`;
    }
  }

  // Wrap unordered list items in <ul>
  html = html.replace(/<li>(.*?)<\/li>(?!<\/ul>)/g, "<li>$1</li>");
  html = html.replace(/(<li>.*?<\/li>)+/g, "<ul>$&</ul>");

  // Wrap ordered list items in <ol>
  html = html.replace(/<li>(.*?)<\/li>(?!<\/ol>)/g, "<li>$1</li>");
  html = html.replace(/(<li>.*?<\/li>)+/g, "<ol>$&</ol>");


  // Inline formatting (bold, italic)

  // Bold (**)
  html = html.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");

  // Italic (*)
  html = html.replace(/\*(.*?)\*/g, "<em>$1</em>");
  
    // Bold (__)
  html = html.replace(/__(.*?)__/g, "<b>$1</b>");

  // Italic (_)
  html = html.replace(/_(.*?)_/g, "<em>$1</em>");

  //Links
  html = html.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');

  //Code blocks

  const codeBlockRegex = /```(.*?)```/s;
  html = html.replace(codeBlockRegex, (match, code) => {
    return `<pre><code>${code.trim()}</code></pre>`;
  });

  // Images
  html = html.replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1">');

  return html;
}


// Example usage:
if (typeof process !== 'undefined' && process.versions['node']) {
  // Running in Node.js
  const markdownExample = `# My Title\n\nThis is a paragraph.\n\n* Item 1\n* Item 2\n\n**Bold text** and *italic text*.\n\n[Link to Google](https://www.google.com)\n\n\`\`\`javascript\nconsole.log("Hello, world!");\n\`\`\``;
  const htmlOutput = markdownToHTML(markdownExample);
  console.log(htmlOutput);
} else {
  // Running in a browser (example)
  const markdownExample = `# My Title\n\nThis is a paragraph.\n\n* Item 1\n* Item 2\n\n**Bold text** and *italic text*.\n\n[Link to Google](https://www.google.com)\n\n\`\`\`javascript\nconsole.log("Hello, world!");\n\`\`\``;
  const htmlOutput = markdownToHTML(markdownExample);
  document.body.innerHTML = htmlOutput;
}
```
👁️ Viewed: 8

Comments