@suryadarsan/html-to-md
Version:
A lightweight package for converting HTML to Markdown, compatible with Vanilla JS and popular frameworks/libraries like Angular, React, and Node.js.
2 lines (1 loc) • 1.5 kB
JavaScript
"use strict";exports.htmlToMd=function(e){let a;if("string"==typeof e){a=(new DOMParser).parseFromString(e,"text/html").body}else a=e;let r="";return function e(a,s=""){var c,t,n,o;if(a.nodeType===Node.TEXT_NODE){let e=null!==(c=a.textContent)&&void 0!==c?c:"";return"pre"!==s&&"code"!==s&&(e=e.replace(/\s+/g," ").trim()),void(e&&(r+=e))}if(a.nodeType===Node.ELEMENT_NODE){const c=a,l=c.tagName.toLowerCase();switch(["p","h1","h2","h3","h4","h5","h6","blockquote","pre"].includes(l)&&(r+="\n\n"),l){case"h1":r+="# ";break;case"h2":r+="## ";break;case"h3":r+="### ";break;case"h4":r+="#### ";break;case"h5":r+="##### ";break;case"h6":r+="###### ";break;case"b":case"strong":r+=" **";break;case"i":case"em":r+=" *";break;case"a":r+=" [";break;case"img":return void(r+=`)&&void 0!==n?n:""})`);case"ul":case"ol":r+="\n";break;case"li":r+="ol"===s?"\n1. ":"\n- ";break;case"code":r+="`";break;case"pre":r+="\n```\n";break;case"blockquote":r+="\n> "}switch(Array.from(c.childNodes).forEach((a=>e(a,l))),l){case"strong":case"b":r+="** ";break;case"em":case"i":r+="* ";break;case"a":r+=`](${null!==(o=c.getAttribute("href"))&&void 0!==o?o:""}) `;break;case"code":r+="`";break;case"pre":r+="\n```\n";break;case"ul":case"ol":r+="\n"}}}(a),r.replace(/\s*\n\s*\n\s*/g,"\n\n").replace(/(?<!\*)\*\s(?!\*)/g,"*").replace(/(?<!\*)\*\*(?!\s)/g,"**").replace(/(?<!-)-\s+(?!-)/g,"- ").replace(/(\n\s*)```/g,"\n```").trim()};