Search code examples
markdownnuxt.jsanchor

How to parse Markdown anchor tags


I'm using markdown to write a blog post. It seems to parse the original text using some set or rules, like:

  • space --> dash
  • UpperCase --> lowercase
  • special characters --> remove or ascii encoding

So, for a header like this:

# Hi, I'm José

I need to write a code like this:

[Click me](#hi-im-jos%C3%A9)

That's not so much intuitive. So, currently I need to:

  • Create the header
  • Generate the page
  • Inspect the page
  • Find the element
  • Copy the href
  • Paste into the anchor tag

What I wish:

  • Create the header
  • Somehow parse the header text to get the correct href
  • Write the anchor tag correctly

I'm using Nuxt.js Content.


Solution

  • A quick way to get visibility on these anchors would be to add a hook in nuxt.config.js. That way you can can see the ids printed in your console without having to inspect the DOM element.

    {
      hooks: {
        "content:file:beforeInsert": document => {
          document.toc.forEach(item => {
            console.log(`${item.text} > #${encodeURI(item.id)}`);
          });
        }
      }
    }
    

    Would output this in the console:

    Hi, I'm José > #hi-im-jos%C3%A9