简体   繁体   中英

jQuery escape certain html entities only

I have a little profile system with mentions in place

The 'content' value in my Posts table is stored as:

<a href="/profile/Alice">Alice</a> Alice, you there? &lt;strong&gt;lol&lt;/strong&gt;
  • the a href Profile link is generated by my system (I replace all mentions with a html link to the profile)
  • the <strong>lol</strong> are user-defined HTML that I do not wish to display (I use htmlentities() on all user-posts so their html input becomes that)

However, the end-result is everything being shown as HTML (I display them using json and jquery). How can I make it such that it only shows the in HTML (for my mention links), but not all the user-specified ones? (ie <strong>)

I want the post to display the mentions in hyper link, but at the same time, I do not want all user entered html to be displayed as html.

I use jQuery append to display my posts.

Thanks!

$str = '<a href="/profile/Alice">Alice</a> Alice, you there? &lt;strong&gt;lol&lt;/strong&gt;';
$str = html_entity_decode($str);
echo $str;
exit;

If I understand what you want, I think this will do it. find("*") only matches HTML tags, so the text nodes outside the tags are filtered out.

 var content = '<a href="/profile/Alice">Alice</a> Alice, you there? &lt;strong&gt;lol&lt;/strong&gt;'; var wrapped = $("<div>", { html: content }); $("#output").append(wrapped.find("*")); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="output"></div> 

I wrap it in a DIV first, because .find() only searches children, not the top-level nodes.

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