markup-it
markup-it
is a JavaScript library to parse and modify markuped content (for example Markdown) using an intermediate format backed by an immutable model.
Installation
$ npm i markup-it --save
Usage
Initialize a syntax:
var MarkupIt = require('markup-it');
var markdownSyntax = require('markup-it/syntaxes/markdown');
var htmlSyntax = require('markup-it/syntaxes/html');
var markdown = new MarkupIt(markdownSyntax);
var html = new MarkupIt(htmlSyntax);
Parse a text
var content = markdown.toContent('Hello **World**');
Render content to HTML/Markdown
var textMd = markdown.toText(content);
var textHtml = html.toText(content);
Convert HTML into Markdown
var content = html.toContent('Hello <b>World</b>');
var textMd = markdown.toText(content);
Usage with Slate
const Slate = require('slate');
var rawJson = MarkupIt.SlateUtils.encode(content);
var state = Slate.Raw.deserialize(rawJson);
And output markdown from a State using SlateUtils.decode
:
var rawJson = Slate.Raw.serialize(state);
var content = MarkupIt.SlateUtils.decode(rawJson);
var text = markdown.toText(content);
Extend Syntax
This module contains the markdown syntax, but you can write your custom syntax or extend the existing ones.
Create rules
var myRule = MarkupIt.Rule(DraftMarkup.BLOCKS.HEADING_1)
.regExp(/^<h1>(\S+)<\/h1>/, function(state, match) {
return {
tokens: state.parseAsInline(match[1])
};
})
.toText(function(state, token) {
return '<h1>' + state.renderAsInline(token) + '</h1>';
});
Custom Syntax
Create a new syntax inherited from the markdown one:
var mySyntax = markdownSyntax.addBlockRules(myRule);
Checkout the GitBook syntax as an example of custom rules extending a syntax.