简体   繁体   English

javascript替换允许的html标签

[英]javascript replace allowed html tags

I need to use javascript to remove all html tags, except for those I explicitly allow. 我需要使用javascript删除所有html标签,除了我明确允许的那些。 I have a form that only allows the following tags and their respective end tags: 我有一个表单,只允许以下标签及其各自的结束标签:

<b> <strong> <i> <em> <u> <br> <pre>
<blockquote> <ol> <ul> <li> 
<a href="http://www.somesite.com">link</a>

All other markup should be removed. 应删除所有其他标记。 I have been searching but I have only found instances where all tags are removed or a single tag is removed. 我一直在搜索,但我只找到了删除所有标签或删除单个标签的实例。 Can this be done simply? 这可以简单地完成吗? I cannot use PHP, must be javascript. 我不能使用PHP,必须是javascript。 Any solutions? 有解决方案吗

Thanks! 谢谢!

so sipping all form of security witch im gessing is why you are doing it in the first place 因此,啜饮所有形式的安全女巫,这就是为什么你这样做的原因

you can put the content in a div and call 你可以将内容放入div并调用

$('#container :not(b, strong, em, u, br, pre, blockquote, ol, ul, li, a)').remove();
var res = $("#container").html();
jQuery.fn.removeTags = function()
{
    this.each(function()
    {
        if(jQuery(this).children().length == 0)
        {
            jQuery(this).replaceWith(jQuery(this).text());
        }
        else
        {
            jQuery(this).children().unwrap();
        }
    });
    return this;
};

jQuery("#container").find(":not(b, strong, i, em, u, br, pre, blockquote, ul, ol, li, a)").removeTags();

Make sure the container is nothing higher than the body tag. 确保容器不高于body标签。 Or you might have issues when it takes out head , html , script etc. tags. 或者,当它取出headhtmlscript等标签时,你可能会遇到问题。

Also if you want the :not could be a list and you could: 此外,如果你想要:不是一个列表,你可以:

var mylist = ["b" ,"strong", ... etc. etc.];
jQuery(":not(" + mylist.join(", ") + ")").removeTags();

Or even put this in the removeTags function. 甚至把它放在removeTags函数中。 (the possibilities are endless ... ) (可能性是无止境 ... )

EDIT: as some have noted in the comments: Javascript can be turned off. 编辑:正如一些人在评论中指出:Javascript可以关闭。 The other thing is I assumed you wanted to keep all the inner information. 另一件事是我认为你想要保留所有内部信息。 If not then just a remove() will suffice as megakorre suggests. 如果没有那么只需一个remove()就足够了,就像megakorre所说的那样。

As pointed out in the comments, this can't be done securely. 正如评论中指出的那样,这不能安全地完成。 It will be very easy to to circumvent the javascript filter. 绕过javascript过滤器很容易。 This must be implemented server side. 这必须在服务器端实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM