Convert between Markdown elements

后端 未结 5 545
借酒劲吻你
借酒劲吻你 2021-01-11 19:52

What are the options to parse Markdown document and process its elements to output an another Markdown document?

Let\'s say it

```
# unaffected #
``         


        
5条回答
  •  感动是毒
    2021-01-11 20:30

    Have you considered using HTML as an intermediate format? Once in HTML, the differences between the header types will be indistinguishable, so the Markdown -> HTML conversion will effectively normalize them for you. There are markdown -> HTML converters aplenty, and also a number of HTML -> markdown.

    I put together an example using these two packages:

    • https://www.npmjs.com/package/markdown-it for Markdown -> HTML
    • https://www.npmjs.com/package/h2m for HTML -> Markdown

    I don't know if you have any performance requirements here (read: this is slow...) but this is a very low investment solution. Take a look:

    var md = require('markdown-it')(),
        h2m = require('h2m');
    
    var mdContent = `
    \`\`\`
    # unaffected #
    \`\`\`
    
    # H1 #
    
    H1
    ==
    
    ## H2 ##
    
    H2
    --
    
    ### H3 ###
    `;
    
    var htmlContent = md.render(mdContent);
    var newMdContent = h2m(htmlContent, {converter: 'MarkdownExtra'});
    console.log(newMdContent);
    

    You may have to play with a mix of components to get the correct dialect support and whatnot. I tried a bunch and couldn't quite match your output. I think perhaps the -- is being interpreted differently? Here's the output, I'll let you decide if it is good enough:

    ```
    # unaffected #
    
    ```
    
    # H1 #
    
    # H1 #
    
    ## H2 ##
    
    ## H2 ##
    
    ### H3 ###
    

提交回复
热议问题