Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Strip all regular html tags except <a></a>, <img>(attributes inside) and <br> with javascript?

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.

Note: I need the design panel, I know its possible to remove it but this is not the case :)

It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.

Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.

Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:

<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">

How can I accomplish this with javascript?

I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.

public string Strip(string text)
{
   return Regex.Replace(text, @"<(?!br[\x20/>])[^<>]+>", string.Empty);
}

Any kind of help is appreciated alot

like image 609
Obsivus Avatar asked Aug 08 '13 14:08

Obsivus


2 Answers

Does this do what you want? http://jsfiddle.net/smerny/r7vhd/

$("body").find("*").not("a,img,br").each(function() {
    $(this).replaceWith(this.innerHTML);
});

Basically select everything except a, img, br and replace them with their content.

like image 56
Dallas Avatar answered Nov 02 '22 22:11

Dallas


Smerny's answer is working well except that the HTML structure is like:

var s = '<div><div><a href="link">Link</a><span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
    $(this).replaceWith(this.innerHTML);
});
console.log($s.html());

The live code is here: http://jsfiddle.net/btvuut55/1/

This happens when there are more than two wrapper outside (two divs in the example above).

Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.

This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.

A working solution is simple: loop from the most inner element towards outside:

var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
    var e = $elements[i];
    $(e).replaceWith(e.innerHTML);
}

The working copy is: http://jsfiddle.net/btvuut55/3/

like image 33
Joy Avatar answered Nov 02 '22 22:11

Joy