处理富文本中图片的样式

428 阅读1分钟
// 处理富文本中 img 的样式
export function fixImgInRichText(htmlSnip) {
    let regex1 = new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)", "gmi");
    // 给不含 style="" 或 style='' 的 img 标签加上 style=""
    htmlSnip = htmlSnip.replace(regex1, "$2 style=\"\"$3");
    // 正则匹配含有 style 的 img 标签
    let regex2 = new RegExp("(i?)(\<img.*?style=['\"])([^\>]+\>)","gmi");
    htmlSnip = htmlSnip.replace(regex2, "$2max-width: 100vw;height: auto; width: 100%; margin: 0 auto;$3");
    return htmlSnip
}