需求:现用字符串和base64图片混合在一起的字符串,如:
let str = "hello <img src=\"data:image/jpg;base64,xxx这是base64内容xxx\" style=\"max-width:100%;\">hahaha...
其中,文本内容和图片内容可以多个,相互混在一起,现在需要把图片用特殊字符:[image] 来替换,最终替换结果如下:
let str = "hello [image]hahaha..."
要求js用正则表达式替换指定字符串,使用最短匹配。
let str = '你好<img src="https://img-blog.csdnimg.cn/2022010616061887665.jpeg" style="max-width: 100%;">微信号是<img src="https://img-blog.csdnimg.cn/2022010616061887665.jpeg" style="max-width:100%;"> qunzhu-licai'
let regStr = /<img src="data:image[\s\S]*?style="max-width:[\s]*?100%;">/gi;
let res = str.replace(regStr, ' *** ');
console.log('res=' + res);
//输出结果:你好[image]微信号是[image] qunzhu-licai
解析:[\s\S]*是匹配任意长度的字符串,后面加个?,那就好匹配到最短的符合条件的字符串。
如果不加?,改成这样:
let regStr = /<img src="data:image[\s\S]*style="max-width:[\s]*100%;">/gi;
则结果为:你好[image] qunzhu-licai
也就是说,没有问号?,正则表达式就默认按照贪婪匹配的方法去寻找符合条件的字符串。