in order to preserve expansibility, this is probably the way of thinking.
/*
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']));
I don't know the answer above
//
//js
var reg = '/<([A-Za-z]+)[^>]+((class|style|controls)=".*?")([^>]+)?>/g';
str.replace(reg,'<$1 $2>');
//php
$reg = '/<([A-Za-z]+)[^>]+((class|style|controls)=".*?")([^>]+)?>/';
echo htmlspecialchars((preg_replace_callback($reg, function ($matches) {
return '<' . $matches[1] . ' ' . $matches[2] . '>';
}, $str)));
style
var reg = /style="(?:((?:background|color)[^;"]+;)+)?((?:(?!background|color)[^;"]+;)+)?(?:((?:background|color)[^;"]+;)+)?((?:(?!background|color)[^;"]+;)+)?/g;
str.replace(reg,function(){
return 'style="'+(arguments[1] || '')+(arguments[3] || '');
});
, but I think since it's for html, it's better to use dom instead of regular. I always feel that there is a lot of abuse of regularities here