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


当前回答

扩展String类:

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

And use as method:

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

其他回答

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

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

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

Ext.util.Format.htmlDecode(innerHtmlContent)

Use

myString = myString.replace( /\&amp;/g, '&' );

在服务器端最容易做到这一点,因为JavaScript显然没有用于处理实体的原生库,我也没有在搜索结果的顶部找到任何扩展JavaScript的框架。

搜索“JavaScript HTML实体”,你可能会找到一些用于此目的的库,但它们可能都是围绕上述逻辑构建的——逐个实体替换。

您不需要jQuery来解决这个问题,因为它会产生一些开销和依赖。

我知道这里有很多好的答案,但由于我实现了一个有点不同的方法,我想分享一下。

这段代码是一种非常安全的安全方法,因为转义处理程序依赖于浏览器,而不是函数。因此,如果将来会发现某些漏洞,则覆盖此解决方案。

const decodeHTMLEntities = text => {
    // Create a new element or use one from cache, to save some element creation overhead
    const el = decodeHTMLEntities.__cache_data_element 
             = decodeHTMLEntities.__cache_data_element 
               || document.createElement('div');
    
    const enc = text
        // Prevent any mixup of existing pattern in text
        .replace(/⪪/g, '⪪#')
        // Encode entities in special format. This will prevent native element encoder to replace any amp characters
        .replace(/&([a-z1-8]{2,31}|#x[0-9a-f]+|#\d+);/gi, '⪪$1⪫');

    // Encode any HTML tags in the text to prevent script injection
    el.textContent = enc;

    // Decode entities from special format, back to their original HTML entities format
    el.innerHTML = el.innerHTML
        .replace(/⪪([a-z1-8]{2,31}|#x[0-9a-f]+|#\d+)⪫/gi, '&$1;')
        .replace(/⪪#/g, '⪪');
   
    // Get the decoded HTML entities
    const dec = el.textContent;
    
    // Clear the element content, in order to preserve a bit of memory (in case the text is big)
    el.textContent = '';

    return dec;
}

// Example
console.log(decodeHTMLEntities("<script>alert('&awconint;&CounterClockwiseContourIntegral;&#x02233;&#8755;⪪#x02233⪫');</script>"));
// Prints: <script>alert('∳∳∳∳⪪#x02233⪫');</script>

顺便说一下,我选择使用字符⪪和⪫,因为它们很少被使用,因此通过匹配它们影响性能的几率显著降低。

试试这个:

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,因为它将在所有情况下工作(小字符串或大字符串)。