我如何使用jQuery解码字符串中的HTML实体?


当前回答

我认为这与我们选择的解决方案完全相反。

var decoded = $("<div/>").text(encodedStr).html();

其他回答

就像Mike Samuel说的,不要使用jQuery.html().text()来解码html实体,因为这是不安全的。

相反,使用模板渲染器,如Mustache.js或decodeEntities从@VyvIT的评论。

js实用带库提供了escape和unescape方法,但它们对用户输入不安全:

_.escape(string)

_.unescape(string)

扩展String类:

String::decode = ->
  $('<textarea />').html(this).text()

And use as method:

"&lt;img src='myimage.jpg'&gt;".decode()

假设下面有String。

我们的豪华客舱温暖,舒适&舒适的

var str = $("p").text(); // get the text from <p> tag
$('p').html(str).text();  // Now,decode html entities in your variable i.e 

STR和赋值回给标签。 就是这样。

你必须为html实体定制函数:

function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g,'&gt;').replace(/"/g, '&quot;');
}

我只需要有一个HTML实体字符(⇓)作为HTML按钮的值。HTML代码在浏览器中从一开始就看起来很好:

<input type="button" value="Embed & Share  &dArr;" id="share_button" />

现在我添加了一个切换,也应该显示字符。这就是我的解

$("#share_button").toggle(
    function(){
        $("#share").slideDown();
        $(this).attr("value", "Embed & Share " + $("<div>").html("&uArr;").text());
    }

这将在按钮中再次显示⇓。我希望这能帮助到一些人。