郎朗坤
为了保留拓展性,大概思路可以这样。/*
reserveAttr 需要保留的属性,null表示全保留
reserveStyle 需要保留的style中的具体样式,null表示全保留
*/function formateHtml(str="", reserveAttr=[], reserveStyle=[]){ return str.replace(/(<[\w|-]+)(.*?)(\/?>)/ig,(...arg)=>arg[1] + arg[2].replace(/([\w|-]+)((=)(['|"])(.*?)(['|"]))?/ig,(...attr)=>!reserveAttr || reserveAttr.includes(attr[1].toLowerCase()) ? (['style'].includes(attr[1].toLowerCase()) ? (attr[1] + attr[3] + attr[4] + attr[5].replace(/([\w|-]+)\s*:[^;]+;?/ig,(...style)=>!reserveStyle || reserveStyle.includes(style[1].toLowerCase()) ? style[0] : '') + attr[6]) : attr[0] ) : '') + arg[3]);
}
//测试例子var str = `<a> </a><img :src="imgSrc" draggable style="background:red;width:500;color:blue"/>文本<img src="src1" style="color:red;" /><IMG :STYLE="SRC2" /><el-input v-Model="val"></el-input><bb src="bbsrc" disabled >bb内容</bb>`;console.log(formateHtml(str,['style','src','controls'],['background','color']));