Introduction to markdown-it
markdown-it is a powerful and flexible Markdown parser written in JavaScript. It provides a highly extensible and customizable way to parse markdown text into HTML.
1. Parse Basic Markdown
markdown-it allows you to convert basic Markdown text into HTML with ease.
const MarkdownIt = require('markdown-it'); const md = new MarkdownIt(); const result = md.render('# Hello World'); console.log(result);
2. Enable Plugins
Extend the functionality using plugins:
const MarkdownIt = require('markdown-it'); const emoji = require('markdown-it-emoji'); const md = new MarkdownIt(); md.use(emoji); const result = md.render('I :heart: Markdown-it!'); console.log(result);
3. Syntax Highlighting
Integrate syntax highlighting for code blocks:
const MarkdownIt = require('markdown-it'); const hljs = require('highlight.js'); const md = new MarkdownIt({ highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { try { return '
' + hljs.highlight(lang, str, true).value + '
';
} catch (__) {}
}
return '' + md.utils.escapeHtml(str) + '
';
}
}); const result = md.render('```javascript\nconsole.log("Hello World");\n```'); console.log(result);4. Custom Rules
Define custom rules for parsing:
const MarkdownIt = require('markdown-it'); const md = new MarkdownIt(); md.inline.ruler.push('example', function (state, silent) { // Custom parsing logic return false; }); const result = md.render('Custom markdown'); console.log(result);
App Example
Using markdown-it, you can build a simple Markdown editor:
<html> <head> <title>Markdown Editor</title> </head> <body> <textarea id="editor"># Welcome to Markdown Editor</textarea> <div id="preview"></div> <script src="https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.min.js"></script> <script> const md = window.markdownit(); const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); editor.addEventListener('input', function() { preview.innerHTML = md.render(editor.value); }); preview.innerHTML = md.render(editor.value); </script> </body> </html>