skip to Main Content

When I have a markdown file with:

![[20230613_110437.jpg]]

in it, and I render it to html with

const html = marked.parse(content);

the html content just contains ![[20230613_110437.jpg]] rather than the image tag.

Also, the image urls should be prefixed with images/, but I don’t see a way to configure that.

How do I configure marked to convert this to:

<img src="images/20230613_110437.jpg" />

2

Answers


  1. marked.js does not parse image syntax in Markdown files by default.
    To enable this feature, you can use the renderer option to customize the rendering of elements.

    Try this configuration to parse image syntax and prefix image URLs with images/:

    const marked = require('marked');
    const path = require('path');
    
    const renderer = new marked.Renderer();
    renderer.image = function(href, title, text) {
      // const url = href.startsWith('http') ? href : `images/${href}`; // for external links
      // return `<img src="${url}" alt="${text}" title="${title}" />`;
    
      const imagePath = path.join(__dirname, 'images', href);
      return `<img src="${imagePath}" src="${imagePath}" alt="${text}" title="${title}" />`; // for local references
    };
    
    const markdown = `![[20230613_110437.jpg]]`;
    const html = marked(markdown, { renderer });
    
    console.log(html);
    
    Login or Signup to reply.
  2. I’m not sure if ![[20230613_110437.jpg]] is an actual markdown. Why not just add images in the format of ![]() like:

    ![image](https://via.placeholder.com/200.png)
    

    That renders to:

    image`

    marked.use({
        headerIds: false,
        mangle: false,
    });
    
    document.getElementById("content").innerHTML = marked.parse(`![image](https://via.placeholder.com/200.png)`);
    console.log(marked.parse(`![image](https://via.placeholder.com/200.png)`));
    <html>
        <body>
            <div id="content"></div>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/5.1.0/marked.min.js"></script>
        </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search