Todd Wolfson

Software Engineer

November 02, 2013

In GitHub, Markdown headers are automatically linked. To achieve the same effect with the marked node module, you need to override part of the lexer.

// Modify marked's tokenizer to wrap header text in an `<a>`
var _tok = marked.Parser.prototype.tok;
marked.Parser.prototype.tok = function () {
  // If this is a heading, use our custom parser
  // https://github.com/chjj/marked/blob/v0.2.10/lib/marked.js#L845-L855
  // NOTE: This is for marked@0.2.10
  if (this.token.type === 'heading') {
    var slug = this.token.text.toLowerCase().replace(/[^\w]+/g, '-');
    return '<h'
          + this.token.depth
          + ' id="'
          + slug
          + '">'
          + '<a href="#' + slug + '">'
          + this.inline.output(this.token.text)
          + '</a>'
          + '</h'
          + this.token.depth
          + '>\n';
  }

  // Otherwise, run the normal function
  return _tok.apply(this, arguments);
};

The end result is:

marked.parse('# Hello World');
/*
<h1 id="hello-world">
  <a href="#hello-world">Hello World</a>
</h1>
*/

Top articles

Lessons of a startup engineer

Lessons from being a 3x first engineer, former Uber engineer, and working at even more startups

Develop faster

Removing the tedium from creating, developing, and publishing repos.

Sexy bash prompt

A bash prompt with colors, git statuses, and git branches.