现在是
加载中...
加载中...

问题复现

// 定义原始图片链接和新图片链接
const img = "![image](http://127.0.0.1:6806/assets/image-20240330091153-5d8kt15.png)"
const newImg = "![image](http://onu1xvsy0.bkt.clouddn.com/test/20240330091641..png)"
let newcontent = "![image](http://127.0.0.1:6806/assets/image-20240330091153-5d8kt15.png)"

// 创建用于匹配原始图片链接的正则表达式
const imgRegex = new RegExp(img, "g")
console.log("imgRegex =>", imgRegex)

// 尝试替换内容中的图片链接
newcontent = newcontent.replace(imgRegex, newImg)
console.log("newcontent =>", newcontent) 

先看一下这个代码,我们的期望是图片链接能够正常替换,但是运行之后就会发现,根本不是我们期望的那样。

// 期望的结果
newcontent =>![image](http://onu1xvsy0.bkt.clouddn.com/test/20240330091641..png)

// 实际的结果
newcontent => ![image](http://127.0.0.1:6806/assets/image-20240330091153-5d8kt15.png)

原因分析

问题就出现在由于原始图片链接中包含特殊字符,如斜杠和点,这些字符在正则表达式中具有特殊含义,可能导致匹配失败。需要对原始图片链接中的特殊字符进行转义处理,以确保正则表达式能够正确匹配。

正则的这个构造方法需要自己处理转义字符问题。因此,我们得到下列修复方法:

image.png

现在,我们已经可以得到正确结果了:

imgRegex => /![image](assets\/image-20240330091153-5d8kt15.png)/g
newcontent => ![image](http://127.0.0.1:6806/assets/image-20240330091153-5d8kt15.png)
newcontent after fix => ![image](http://onu1xvsy0.bkt.clouddn.com/test/20240330091641..png)

MDN 解释

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#flags_in_constructor

作者:Terwer

首发:浅海拾贝

原创内容,转载请注明出处!

评论