Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

jquery - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...