简体   繁体   中英

javascript replace allowed html tags

I need to use javascript to remove all html tags, except for those I explicitly allow. 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. 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

$('#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. Or you might have issues when it takes out head , html , script etc. tags.

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. (the possibilities are endless ... )

EDIT: as some have noted in the comments: Javascript can be turned off. 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.

As pointed out in the comments, this can't be done securely. It will be very easy to to circumvent the javascript filter. This must be implemented server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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