Unescape HTML entities in Javascript?

前端 未结 30 2920
野趣味
野趣味 2020-11-21 05:40

I have some Javascript code that communicates with an XML-RPC backend. The XML-RPC returns strings of the form:


30条回答
  •  野性不改
    2020-11-21 05:46

    CMS' answer works fine, unless the HTML you want to unescape is very long, longer than 65536 chars. Because then in Chrome the inner HTML gets split into many child nodes, each one at most 65536 long, and you need to concatenate them. This function works also for very long strings:

    function unencodeHtmlContent(escapedHtml) {
      var elem = document.createElement('div');
      elem.innerHTML = escapedHtml;
      var result = '';
      // Chrome splits innerHTML into many child nodes, each one at most 65536.
      // Whereas FF creates just one single huge child node.
      for (var i = 0; i < elem.childNodes.length; ++i) {
        result = result + elem.childNodes[i].nodeValue;
      }
      return result;
    }
    

    See this answer about innerHTML max length for more info: https://stackoverflow.com/a/27545633/694469

提交回复
热议问题