Jaki jest właściwy sposób dekodowania ciągu znaków, który zawiera specjalne encje HTML? [duplikat]

to pytanie ma już odpowiedzi tutaj : Unescape encje HTML w Javascript? (30 odpowiedzi) Zamknięty 3 lata temu .

Powiedzmy, że odzyskam JSON z żądania serwisowego, które wygląda tak:

{
    "message": "We're unable to complete your request at this time."
}

Nie jestem pewien dlaczego ten apostrof jest zakodowany w ten sposób ('); wiem tylko, że chcę go odkodować.

Oto jedno podejście wykorzystujące jQuery, które wpadło mi do głowy:

function decodeHtml(html) {
    return $('<div>').html(html).text();
}
To wydaje się (bardzo) trudne. Co jest lepszym sposobem? Czy istnieje "właściwy" sposób?
Author: Dan Tao, 2011-09-12

7 answers

To mój ulubiony sposób dekodowania znaków HTML. Zaletą tego kodu jest to, że tagi są również zachowane.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Przykład: http://jsfiddle.net/k65s3/

Wejście:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Wyjście:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
 424
Author: Rob W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-04 18:55:04

Nie używaj do tego DOM. Używanie DOM do dekodowania encji HTML (zgodnie z sugestią w aktualnie akceptowanej odpowiedzi) prowadzi do różnic w wynikach między przeglądarkami .

Dla solidnego i deterministycznego rozwiązania, które dekoduje odwołania do znaków zgodnie z algorytmem w standardzie HTML, użyj he . Z jego README:

he (dla "encji HTML") jest solidnym koderem/dekoderem encji HTML napisanym w JavaScript. Obsługuje wszystkie znormalizowane odwołania do nazwanych znaków zgodnie z HTML, obsługuje niejednoznaczne ampersandy i inne przypadki krawędzi , podobnie jak przeglądarka , ma obszerny zestaw testów i - w przeciwieństwie do wielu innych rozwiązań JavaScript - on obsługuje Astralne symbole Unicode. demo online jest dostępne.

Oto jak go wykorzystasz:

he.decode("We&#39;re unable to complete your request at this time.");
→ "We're unable to complete your request at this time."

Zastrzeżenie: jestem autorem on biblioteki.

Zobacz ta odpowiedź przepełnia stos {[5] } aby uzyskać więcej informacji.

 139
Author: Mathias Bynens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-05 05:52:37

Jeśli nie chcesz używać html / dom, możesz użyć regex. Nie testowałem tego, ale coś w stylu:

function parseHtmlEntities(str) {
    return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
        var num = parseInt(numStr, 10); // read num as normal number
        return String.fromCharCode(num);
    });
}

[edytuj]

Uwaga: będzie to działać tylko dla numerycznych encji html, a nie takich jak & oring;.

[edytuj 2]

Poprawiono funkcję (niektóre literówki), test tutaj: http://jsfiddle.net/Be2Bd/1/

 38
Author: Alxandr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-13 21:59:15

JQuery będzie kodować i dekodować dla Ciebie.

function htmlDecode(value) {
  return $("<textarea/>").html(value).text();
}

function htmlEncode(value) {
  return $('<textarea/>').text(value).html();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $("#encoded")
  .text(htmlEncode("<img src onerror='alert(0)'>"));
   $("#decoded")
  .text(htmlDecode("&lt;img src onerror='alert(0)'&gt;"));
});
</script>

<span>htmlEncode() result:</span><br/>
<div id="encoded"></div>
<br/>
<span>htmlDecode() result:</span><br/>
<div id="decoded"></div>
 29
Author: Jason Williams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-12 15:38:11

Istnieje funkcja JS do obsługi & # xxxx :
function at GitHub

// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
  return str.replace(/&#(\d+);/g, function(match, dec) {
    return String.fromCharCode(dec);
  });
};

var encodeHtmlEntity = function(str) {
  var buf = [];
  for (var i=str.length-1;i>=0;i--) {
    buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
  }
  return buf.join('');
};

var entity = '&#39640;&#32423;&#31243;&#24207;&#35774;&#35745;';
var str = '高级程序设计';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
 26
Author: hypers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-12 23:24:14

_.unescape robi to, czego szukasz

Https://lodash.com/docs/#unescape

 10
Author: tldr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-15 16:22:10

To bardzo dobra odpowiedź. Możesz użyć tego z angular w ten sposób:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);
 -1
Author: kodmanyagha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 13:58:10