匹配html字符串中的img标签并居中

replaceImg.js

export function replaceImg  ({str, width=200, height=300}) {
           str = str.replace(/(<img[^>]*>)|(<img[^>]*><\/img>)/g, function(match, capture){
                if(match.indexOf('style') < 0 ){
                  // 没有style 就添加一个
                    return match.replace(/<\s*img/, '<img style=""');
                } else {
                  // 有style 就不做处理 直接返回
                    return match
                }
            })
            console.log("增加style=\"\"后的html字符串:"+str);
            str = str.replace(/<img[^>]*>/gi, function (match, capture) {
                return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="width:100%;height:auto;margin:0 auto; display:block;"') // 替换style
            })
            console.log('htmlstr', str)
    return str
}

使用

import { replaceImg } from './replaceImg'
methods: {
    getList() {
      this.html = replaceImg({
          str: this.html,
          width: 300,
          height: 200
      })
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容