/

How to Change Image URLs in a Markdown String

How to Change Image URLs in a Markdown String

When migrating a blog from Hugo to Next.js, I encountered an issue regarding the usage of spaces in image names. While Hugo allowed spaces, Next.js markdown requires hyphens instead. This posed a challenge as I frequently use screenshots with default names like “Screen Shot 2022-…”.

To overcome this limitation, I implemented a script that converted the image names to use hyphens instead of spaces. For example:

1
2
3
"Screen Shot 2022-..." 
=>
"Screen-Shot-2022-..."

I then replaced the post’s markdown content with the updated image names.

Furthermore, I had to modify the image URLs because Next.js does not support having the post in the same folder as the markdown file. To make each post image public, I adopted the format /public/images/<SLUG>/.

Here’s an example of how I achieved this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matter from 'gray-matter'

// ...

let { data: frontmatter, content } = matter(fileName)

const regex = /\!\[(.*?)\]\((.*?)\)/gm
let matches

while ((matches = regex.exec(content)) !== null) {
content = content.replace(
'](' + matches[2],
`](/images/${slug}/${matches[2].replace(/ /g, '-').replace(/\//g, '')}`
)
}

By implementing these changes, I successfully resolved the image URL issue that arose during the migration from Hugo to Next.js.

Tags: image URLs, markdown, migration, Next.js, Hugo