1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| const rules = [ [/#{6}\s?([^\n]+)/g, "<h6>$1</h6>"], [/#{5}\s?([^\n]+)/g, "<h5>$1</h5>"], [/#{4}\s?([^\n]+)/g, "<h4>$1</h4>"], [/#{3}\s?([^\n]+)/g, "<h3>$1</h3>"], [/#{2}\s?([^\n]+)/g, "<h2>$1</h2>"], [/#{1}\s?([^\n]+)/g, "<h1>$1</h1>"],
[/\*\*\s?([^\n]+)\*\*/g, "<strong>$1</strong>"], [/\*\s?([^\n]+)\*/g, "<em>$1</em>"], [ /\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>', ],
[ /(`)(\s?[^\n,]+\s?)(`)/g, '<a style="background-color:grey;color:black;text-decoration: none;border-radius: 3px;padding:0 2px;">$2</a>', ], ]
function markdown2html(markdown = '') { let html = markdown; try { rules.forEach(([rule, template]) => { html = html.replace(rule, template); }); } catch (error) { console.error('转换失败:', error); } return html; }
console.log(markdown2html(` # heading1 ## heading2 ### heading3 #### heading4 ##### heading5 ###### heading6
**strong** *em*
[百度](https://www.baidu.com)
\`highlight\` `));
|