marked: customize parser to render <h2> and following elements in <section>

37 views Asked by At

How to customize marked to make it rendering <h2> tags and following elements in a <section>. If a new <h2> tag appears afterwards, wrap everything in a new <section> again.

exmpale markdown input:

# h1 header

## first h2 header
paragraph
paragraph

## second h2 header
paragraph
paragraph

html output:

<h1>h1 header</h1>

<section>
  <h2>frist h2 header</h2>
  <p>paragrqph</p>
  <p>paragrqph</p>
</section>

<section>
  <h2>second h2 header</h2>
  <p>paragrqph</p>
  <p>paragrqph</p>
</section>
 
1

There are 1 answers

0
wenzf On BEST ANSWER
import { marked } from 'marked'

const str = `markdown from <textarea> input`
const modifiedMarkdown = str.replace(/(##[^#]+)/g, '<section>\n\n$1</section>')
const markdownWithSections = marked.parse(modifiedMarkdown, { mangle: false, headerIds: false })

Based on the answer from here. - added two line breaks after section start