从字符串中删除无效的html标记

时间:2013-07-05 16:16:19

标签: javascript html

有没有办法使用javascript从字符串中删除无效的HTML标记?

例如:<div> <foo></foo> </div>应转换为<div></div>

2 个答案:

答案 0 :(得分:0)

看起来您正在尝试使用自己的HTML清理程序。我不建议这样做。相反,请查看已经要求使用消毒剂的其他问题:Sanitize/Rewrite HTML on the Client Side

具体来说,这里有一个可供使用的地方:https://code.google.com/p/google-caja/wiki/JsHtmlSanitizer

答案 1 :(得分:-2)

试试这个:

<!DOCTYPE html>
<html>
<body>

<p id="demo"><foo></foo></p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML, 
    reg = /<foo>|<\/foo>/i;

str = str.replace(reg, " "); 
document.getElementById("demo").innerHTML=str;
}
</script>

</body>
</html>