Javascript replace allowed html tags

I need to use javascript to remove all html tags except those that I explicitly allow. I have a form that allows only tags and their end tags:

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

All other markups must be removed. I searched, but I only found cases where all tags were deleted or a single tag is deleted. Can this be done simply? I can not use PHP, there must be javascript. Any solutions?

Thank!

0
source share
3 answers
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 no larger than the tag body. Or, you may experience problems when you receive the tags head, html, scriptetc.

Also, if you want: there cannot be a list, and you could:

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

removeTags. ( ...)

EDIT:, : Javascript . , , . , remove() , megakorre.

+1

,

div

$('#container :not(b, strong, em, u, br, pre, blockquote, ol, ul, li, a)').remove();
var res = $("#container").html();
+1

As stated in the comments, this cannot be done reliably. It is very easy to bypass the javascript filter. This should be implemented on the server side.

0
source

Source: https://habr.com/ru/post/1735728/


All Articles