markdown js实现
在JavaScript中实现Markdown解析和渲染可以通过多种方式完成,以下是几种常见的方法:
使用现成的Markdown解析库
marked.js
安装marked.js库:
npm install marked
使用示例:
const marked = require('marked');
const html = marked.parse('# Hello Markdown!');
console.log(html); // 输出: <h1>Hello Markdown!</h1>
markdown-it
安装markdown-it库:
npm install markdown-it
使用示例:
const md = require('markdown-it')();
const html = md.render('# Hello Markdown!');
console.log(html); // 输出: <h1>Hello Markdown!</h1>
自定义简单的Markdown解析器
以下是一个简单的自定义Markdown解析器示例,仅支持标题和段落:
function parseMarkdown(markdown) {
return markdown
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
.replace(/^### (.*$)/gm, '<h3>$1</h3>')
.replace(/^(?!<h[1-3]>)(.*$)/gm, '<p>$1</p>');
}
const html = parseMarkdown('# Title\nThis is a paragraph.');
console.log(html);
在浏览器中实时渲染Markdown
结合HTML和JavaScript实现实时渲染:
<textarea id="markdown-input" rows="10" cols="50"># Hello Markdown!</textarea>
<div id="html-output"></div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.getElementById('markdown-input').addEventListener('input', function() {
const markdown = this.value;
const html = marked.parse(markdown);
document.getElementById('html-output').innerHTML = html;
});
</script>
支持数学公式的Markdown渲染
结合markdown-it和mathjax支持数学公式:

const md = require('markdown-it')({
html: true,
linkify: true,
typographer: true
}).use(require('markdown-it-mathjax')());
const html = md.render('Euler\'s formula: $e^{i\\pi} + 1 = 0$');
console.log(html);
注意事项
- 使用现成的库如marked.js或markdown-it可以覆盖大多数Markdown语法需求。
- 自定义解析器仅适合简单需求,完整实现需要处理大量边缘情况。
- 数学公式需要额外插件或库支持,如MathJax或KaTeX。






