正则表达式:用 Javascript/Node 替换降价字符串中的相对图像 url

Regex: replace relative image urls in markdown string with Javascript/Node

我目前有一些降价 post 是我从 github 存储库中提取的。 post 中的所有图像都是相对 link 编辑的,我需要在相对 URL 前加上 CDN link 全局。

当前: [000](images/000.png)

期望:

[000](https://cdn.jsdelivr.net/gh/gaurangrshah/site-cms@main/images/000.png)

我尝试了几种方法,但由于某种原因似乎无法定位“图像”:

post.matter.content = post?.matter?.content.replace( "图片.*/g", ${imageBase}/images );

String.replace 接受字符串或正则表达式作为第一个参数。您正在传递一个字符串,但您希望它是一个正则表达式。所以只需将replace的第一个参数改成如下:

const post = {
  matter: {
    content: `[000](images/000.png)`
  }
};

const imageBase = "https://cdn.jsdelivr.net/gh/gaurangrshah/site-cms@main";

post.matter.content = post?.matter?.content.replace(
  /images/g,
  `${imageBase}/images`
);

console.log(post.matter.content);

我遇到了一个非正则表达式的解决方案,我在这里分享给后代(也就是我未来的自己)。

post.matter.content = post?.matter?.content.replaceAll('images', `${imageBase}/images`);