js replace 替换路径无效的问题
问题复现
我们先看一段代码
var imageSrc = "F:\md\assets\image-20220418143258134.png";
var url = "https://img2022.cnblogs.com/blog/1652001/202204/1652001-20220418185238494-466983647.png";
fileContent = "F:\\md\\assets\\image-20220418143258134.png1213131";
console.log(fileContent);
console.log(fileContent.replace(imageSrc,url));
运行之后发现
你会发现并没有替换,并且从打印看结果一模一样
解决方法
使用String.raw
详细语法见:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/raw
这时候将上面代码改成
var imageSrc = String.raw`F:\md\assets\image-20220418143258134.png`;
var url = "https://img2022.cnblogs.com/blog/1652001/202204/1652001-20220418185238494-466983647.png";
fileContent = "F:\\md\\assets\\image-20220418143258134.png1213131";
console.log(imageSrc);
console.log(fileContent);
console.log(fileContent.replace(imageSrc,url));
结果如图