推荐一个正则匹配的网站 https://regex101.com/
let str ='有四只小动物排成一排,摄影师给相邻的两只小动物拍了下面三张照片。<img style="vertical-align: middle; width: 712px; height: 99.0337px;" width="1317" height="183" src="http://test.baidu.com/test.png" /><br />(<span class="brack"> </span>)排在最左边,(<span class="brack"> </span>)排在最右边。';// 使用正则表达式匹配style中的width样式,并将大于375的部分替换为375px
let result = str.replace(/(<img[^>]*style="[^"]*?)(\bwidth\s*:\s*\d+[^;"]*?px;)(\s?height\s*:\s*\d+[^;"]*?px;)([^<]*\/>)/gi,function (match, p1, p2, p3, p4) {console.log("🚀 ~ file: test.js:8 ~ p4:", p4);console.log("🚀 ~ file: test.js:8 ~ p3:", p3);console.log("🚀 ~ file: test.js:8 ~ p2:", p2);console.log("🚀 ~ file: test.js:8 ~ p1:", p1);console.log("🚀 ~ file: test.js:8 ~ match:", match);let widthValue = parseInt(p2.match(/\d+/)[0]);let heightValue = parseInt(p3.match(/\d+/)[0]);if (widthValue > 375) {return p1 + "width: 375px; height: auto;" + p4;}return match; // 如果width小于等于375,则不做替换,保持原样}
);
console.log("🚀 ~ file: test.js:20 ~ result:", result);