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


当前回答

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

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

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

_.escape(string)

_.unescape(string)

其他回答

安全注意:使用这个答案(下面保留其原始形式)可能会在您的应用程序中引入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 / >

使用jQuery解码HTML实体,只需使用这个函数:

function html_entity_decode(txt){
    var randomID = Math.floor((Math.random()*100000)+1);
    $('body').append('<div id="random'+randomID+'"></div>');
    $('#random'+randomID).html(txt);
    var entity_decoded = $('#random'+randomID).html();
    $('#random'+randomID).remove();
    return entity_decoded;
}

使用方法:

Javascript:

var txtEncoded = "&aacute; &eacute; &iacute; &oacute; &uacute;";
$('#some-id').val(html_entity_decode(txtEncoded));

HTML:

<input id="some-id" type="text" />

假设下面有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和赋值回给标签。 就是这样。

或者,也有一个库。

在这里,https://cdnjs.com/libraries/he

npm install he                 //using node.js

<script src="js/he.js"></script>  //or from your javascript directory

用法如下…

//to encode text 
he.encode('© Ande & Nonso® Company LImited 2018');  

//to decode the 
he.decode('&copy; Ande &amp; Nonso&reg; Company Limited 2018');

欢呼。

对于ExtJS用户,如果你已经有了编码的字符串,例如当一个库函数的返回值是innerHTML内容时,考虑这个ExtJS函数:

Ext.util.Format.htmlDecode(innerHtmlContent)