美文网首页
匹配html字符串中的img标签并居中

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

作者: 啊柒柒柒 | 来源:发表于2020-01-19 11:21 被阅读0次

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
      })
    }
}

相关文章

网友评论

      本文标题:匹配html字符串中的img标签并居中

      本文链接:https://www.haomeiwen.com/subject/kehrzctx.html