js 匹配 img标签 增加 style样式


给img标签增加 style样式:

1、如果img 标签没有style 就先添加style标签

2、添加标签后统一再添加style样式

   function  imgTagAddStyle (htmlstr) {
      // 正则匹配所有img标签
      // var regex0 = new RegExp("(i?)(\<img)([^\>]+\>)","gmi");
      // 正则匹配不含style="" 或 style='' 的img标签
      // eslint-disable-next-line no-useless-escape
      var regex1 = new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)", 'gmi')
      // 给不含style="" 或 style='' 的img标签加上style=""
      htmlstr = htmlstr.replace(regex1, '$2 style=""$3')
      console.log('增加style=""后的html字符串:' + htmlstr)
      // 正则匹配含有style的img标签
      // eslint-disable-next-line no-useless-escape
      var regex2 = new RegExp("(i?)(\<img.*?style=['\"])([^\>]+\>)", 'gmi')
      // 在img标签的style里面增加css样式(这里增加的样式:display:block;max-width:100%;height:auto;border:5px solid red;)
      htmlstr = htmlstr.replace(regex2, '$2max-width:100%;height:auto;$3')
      console.log('在img标签的style里面增加样式后的html字符串:' + htmlstr)
      return htmlstr
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 JS正则表达式匹配