How to convert markdown to HTML in Javascript using Remarkable

How to convert markdown to HTML in Javascript using Remarkable

Markdown is one of the most commonly used lightweight markup languages on the internet. It is great for a subset of tasks, mainly blog posts and commenting. With just a couple of extra characters, Markdown makes rich document formatting quick and beautiful. Markdown can be converted to HTML in many programming languages, of course we cannot forget our loved Javascript. If you want to convert markdown to HTML easily with Javascript either in the browser, Node.js or other Javascript runtime, then we recommend you to use Remarkable.

Remarkable is a markdown parser done right. It's really fast and easy to extend, as it doesn't pay with speed for it's flexibility because it's written in monomorphic style and uses JIT inline caches effectively. It has a configurable syntax, that means that you can add new rules and even replace existing ones. It follows the CommonMark specifications.

Requirements

To convert markdown easily to HTML in Javascript, you will need as previously mentioned Remarkable. You can download the library with NPM:

npm install remarkable --save

Or With Bower:

bower install remarkable --save

Or if you don't use a package manager, use a CDN (or download the script from the repository in Github here):

<script src="https://cdn.jsdelivr.net/remarkable/1.7.1/remarkable.min.js"></script>

For more information about the library, visit the official Github repository here.

Using Remarkable

Remarkable can be easily in its most basic expression in the following example:

// If you use require (Node etc), require as first the module and then create the instance
var Remarkable = require('remarkable');
// If you're in the browser, the Remarkable class is already available in the window
var md = new Remarkable();

// Outputs: <h1>Remarkable rulezz!</h1>
console.log(md.render('# Remarkable rulezz!'));

Remarkable is configurable to work in the same way that Github Flavored Markdown, however HTML tags are disallowed. You can customize Remarkable in the constructor or with the set method.

Note

If you're worried about the performance of your application, to achieve the best possible performance, don't modify a Remarkable instance on the fly. If you need multiple configurations, create multiple instances and initialize each with a configuration that is ideal for that instance.

Customizing remarkable in the constructor

As mentioned, you can modify the options of remarkable through the constructor:

// Actual default values

var md = new Remarkable({
    html: false, // Enable HTML tags in source
    xhtmlOut: false, // Use '/' to close single tags (<br />)
    breaks: false, // Convert '\n' in paragraphs into <br>
    linkify: false, // Autoconvert URL-like text to links

    // Enable some language-neutral replacement + quotes beautification
    typographer: false,

    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.
    quotes: '“”‘’'
});

console.log(md.render('# Remarkable rulezz!'));

Customizing remarkable through the set method

Alternatively you can modify the properties on the fly using the set method:

var md = new Remarkable();

md.set({
    html: true,
    breaks: true
});

Code syntax highlighting

By default remarkable process code snippets as github does, for example the following markdown:

# Remarkable rulezz!

```javascript 
alert(window.location.host)
```

Would be converted into the following HTML:

<h1>Remarkable rulezz!</h1>
<pre>
    <code class="language-javascript">alert(window.location.host)</code>
</pre>

Which makes the code highlighting easy with plugins like Prism.js or HighlightJS. However, if you want to directly return the highlighted markup (the code already formatted with the highlight spans etc), you can use the highlight function that allows you to customize how the code string should be handled (this feature is specially useful in the server side e.g NodeJS). The following example shows how to highlight directly the code using HighlightJS:

Note

Highlight should return escaped HTML or '' if the source string is not changed.

var md = new Remarkable({
    // Modify the generated HTML by highlighting the code directly
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return hljs.highlight(lang, str).value;
            } catch (err) {}
        }

        try {
            return hljs.highlightAuto(str).value;
        } catch (err) {}

        return ''; // use external default escaping
    }
});

// rest of your code

Which with the markdown example, should generate the following HTML:

<h1>Remarkable rulezz!</h1>
<pre>
    <code class="language-javascript">alert(<span class="hljs-built_in">window</span>.location.host)</code>
</pre>

Pretty easy right?

Using plugins

Remarkable allows you to use plugins and even create your own plugins. To register them in Remarkable just, use the use method:

var md = new Remarkable();

md.use(plugin1)
  .use(plugin2, opts)
  .use(plugin3);

For example, to add the pretty-remarkable plugin (used prettifying markdown with Remarkable using custom renderer rules) you could simply use the following code:

var prettify = require('pretty-remarkable');
var Remarkable = require('remarkable');
var md = new Remarkable();

// register the plugin
md.use(prettify);

// use
var result = md.render('\n\n\n# foo\n\n\nbar\n# baz');
//=> '# foo\n\nbar\n\n# baz'

Happy coding !

Become a more social person