猿问

用正则判断一个小条件,帮帮忙

问题:

把HTML标签中的src style controls属性以外的属性全部替换成空,

**并且**

style里面的属性,只留下 background 和 color 两个style属性 ,其他也全部替换成空,小弟实在不会,先谢谢### 问题描述

问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?


撒科打诨
浏览 461回答 2
2回答

郎朗坤

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

斯蒂芬大帝

//过滤属性//jsvar&nbsp;reg&nbsp;=&nbsp;'/<([A-Za-z]+)[^>]+((class|style|controls)=".*?")([^>]+)?>/g'; str.replace(reg,'<$1&nbsp;$2>');//php$reg&nbsp;=&nbsp;'/<([A-Za-z]+)[^>]+((class|style|controls)=".*?")([^>]+)?>/';echo&nbsp;htmlspecialchars((preg_replace_callback($reg,&nbsp;function&nbsp;($matches)&nbsp;{&nbsp;&nbsp;return&nbsp;'<'&nbsp;.&nbsp;$matches[1]&nbsp;.&nbsp;'&nbsp;'&nbsp;.&nbsp;$matches[2]&nbsp;.&nbsp;'>'; },&nbsp;$str))); 过滤stylevar&nbsp;reg&nbsp;=&nbsp;/style="(?:((?:background|color)[^;"]+;)+)?((?:(?!background|color)[^;"]+;)+)?(?:((?:background|color)[^;"]+;)+)?((?:(?!background|color)[^;"]+;)+)?/g; str.replace(reg,function(){ &nbsp;&nbsp;return&nbsp;'style="'+(arguments[1]&nbsp;||&nbsp;'')+(arguments[3]&nbsp;||&nbsp;''); });
随时随地看视频慕课网APP

相关分类

Html5
我要回答