marked icon indicating copy to clipboard operation
marked copied to clipboard

How to re-parse token to markdown?

Open icefery opened this issue 2 years ago • 1 comments

Question

How to re-parse token to markdown?

I am using marked.lexer() to parse markdown to token, and want to do some changes on it and then re-parse to markdown. As below:

const { marked } = require('marked')

const data = `
# Title
content
`
// parse markdown to token
const tokens = marked.lexer(data)
// get h1 token
const h1 = tokens.find(token => token.type === 'heading' && token.depth === 1)
if (h1) {
  // change h1 token
  h1.text = 'Overview'
  // re-parse token to markdown
  // const result = marked.reParse(tokens)
}

// result should be like this
/*
# Overview
content
*/

Thanks.

icefery avatar Jun 20 '22 08:06 icefery

That isn't what marked is for. You could use turndown on the output HTML. Or you will have to create your own renderer that outputs markdown instead of html.

UziTech avatar Jun 20 '22 14:06 UziTech

An extension would probably work.

Here's a simple example:

const heading = {
  name: 'heading',
  renderer({ depth }) {
    // return false to use default renderer
    return depth === 1 ? '<h1>Overview</h1>' : false;
  },
};

marked.use({ extensions: [heading] });
marked.parse(`# header 1
## header 2`); // <h1>Overview</h1><h2 id="header-2">header 2</h2>

spenserblack avatar Aug 16 '22 14:08 spenserblack