How to change image URLs in a markdown string

By

Learn how to rewrite Markdown image URLs with a JavaScript replace callback while keeping the alt text and optional image title intact.

~~~

I was trying to see if moving my blog (based on Hugo) to Next.js was a good move (it wasn’t) and I found a problem.

Hugo allows me to use spaces in images, which is handy especially as I use screenshots and I get those named as Screen Shot 2022-... by default.

The Next.js markdown does not allow that. So I had a script that converted all images names to use hyphens instead of spaces

"Screen Shot 2022-..." 

=> 

"Screen-Shot-2022-..."

and then I replaced the post markdown content with that.

Also I had to change the URL because Hugo allows a post to be in the same folder as the markdown file, while Next.js does not.

So I used a /public/images/<SLUG>/ folder format to make each post image public.

For a controlled set of Markdown files, a replace() callback is enough:

const imagePattern = /!\[([^\]]*)\]\(([^\s)]+)(\s+["'][^"']*["'])?\)/g

content = content.replace(
  imagePattern,
  (match, alt, imagePath, title = '') => {
    const fileName = imagePath
      .split('/')
      .pop()
      .replaceAll(' ', '-')

    return `![${alt}](/images/${slug}/${fileName}${title})`
  }
)

The callback rewrites only the URL. It leaves the image alt text and optional title in place.

This regular expression is intentionally limited. Markdown permits escaped characters, angle-bracket URLs, and nested syntax that a small regex will not parse reliably. If the input is not under your control or uses those forms, parse it with a Markdown library and transform the image nodes instead.

~~~

Related posts about js: