In my part 1 and part 2 posts, I explained how to create a Markdown renderer that has halfway reasonable code highlighting, and (very) basic charts – in this post, I’m going to explain something I think is quite interesting, custom formatting of string interpolation (I know, it doesn’t roll off the tongue). Basically, using backticks in code (i.e. `hello ${world}`) you can create an interpolated string – the previous example would produce the string “hello” followed by the contents of the variable “world”. At this point, this may seem kind of obvious, and possibly, a little pointless. But, what if we wanted to have a simple way of doing this that ends up formatted as Markdown? Again, this is quite simple, first off, we need to create a function with the following signature:

import { marked } from "marked";

export function MD(strings, ...values) {
    marked.use({async:false});

    let str = "";
    // Create the interpolated string
    for(let i=0;i<strings.length;i++) {
        str += strings[i];
        if(i < values.length) {
            str += values[i];
        }
    }

    // Remove any leading or trailing spaces
    str = str.replace(/^\s+/g,"").replace(/\s+$/g,"");

    // Create the HTML from the created string
    return marked(str);
}

This then allows you (as long as you import the function in the relevant JS) to use MD`# Hello world` in order to render (for example) <h1>Hello world</h1> in HTML.

That’s it. You can, of course, use different rendering pipelines with the same function signature; for example you could have function code(strings, ...values) and then use code`Hello world!` render in a custom format, the only limit is your imagination!