正则替换html img中的style width和height

推荐一个正则匹配的网站 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">&nbsp;</span>)排在最左边,(<span class="brack">&nbsp;</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);


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值