改变markdown字符串中的图片URLs的方法

104 阅读1分钟

我想看看把我的博客(基于Hugo)转移到Next.js是否是一个好的举措(不是),我发现了一个问题。

Hugo允许我在图片中使用空格,这很方便,尤其是我使用屏幕截图,我把这些图片默认命名为Screen Shot 2022-...

Next.js的markdown则不允许这样。因此,我有一个脚本,将所有的图片名称转换为使用连字符而不是空格

"Screen Shot 2022-..." 

=> 

"Screen-Shot-2022-..."

然后我把帖子的标记内容换成了这个。

我还必须改变URL,因为Hugo允许帖子与markdown文件在同一个文件夹里,而Next.js不允许。

所以我使用了/public/images/<SLUG>/ 文件夹格式,使每个帖子的图片都是公开的。

以下是我的做法。

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, '')}`
  )
}