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


当前回答

这里还有一个问题: 转义字符串分配给输入值时看起来不可读

var string = _.escape("<img src=fake onerror=alert('boo!')>");
$('input').val(string);

Exapmle: https://jsfiddle.net/kjpdwmqa/3/

其他回答

我只需要有一个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());
    }

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

试试这个:

var htmlEntities =“<脚本> alert(‘你好’);< /脚本>” html var =$.parseHTML(html)[0][wholeText]; 控制台日志(htmlDecode); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < / >

parseHTML是Jquery库中的一个函数,它将返回一个包含给定字符串的一些细节的数组。

在某些情况下字符串很大,所以函数会将内容分离到多个索引中。

要获得所有索引数据,你应该去任何索引,然后访问名为“wholeText”的索引。

我选择索引0,因为它将在所有情况下工作(小字符串或大字符串)。

安全注意:使用这个答案(下面保留其原始形式)可能会在您的应用程序中引入XSS漏洞。你不应该用这个答案。阅读lucascaro对这个答案中漏洞的解释,并使用该答案或Mark Amery的答案中的方法。

实际上,试一试

var encodedStr = "This is fun &东西”; var解码= $ (" < div / > ") . html (encodedStr)。text (); console.log(解码); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < div / >

您可以使用该库,从https://github.com/mathiasbynens/he获得

例子:

console.log(he.decode("J&#246;rg &amp J&#xFC;rgen rocked to &amp; fro "));
// Logs "Jörg & Jürgen rocked to & fro"

我质疑这个库的作者,是否有任何理由在客户端代码中使用这个库来支持<textarea>黑客提供的其他答案在这里和其他地方。他提供了一些可能的理由:

If you're using node.js serverside, using a library for HTML encoding/decoding gives you a single solution that works both clientside and serverside. Some browsers' entity decoding algorithms have bugs or are missing support for some named character references. For example, Internet Explorer will both decode and render non-breaking spaces (&nbsp;) correctly but report them as ordinary spaces instead of non-breaking ones via a DOM element's innerText property, breaking the <textarea> hack (albeit only in a minor way). Additionally, IE 8 and 9 simply don't support any of the new named character references added in HTML 5. The author of he also hosts a test of named character reference support at http://mathias.html5.org/tests/html/named-character-references/. In IE 8, it reports over one thousand errors. If you want to be insulated from browser bugs related to entity decoding and/or be able to handle the full range of named character references, you can't get away with the <textarea> hack; you'll need a library like he. He just darn well feels like doing things this way is less hacky.

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

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