282

Say I get some JSON back from a service request that looks like this:

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

I'm not sure why that apostraphe is encoded like that ('); all I know is that I want to decode it.

Here's one approach using jQuery that popped into my head:

function decodeHtml(html) {
    return $('<div>').html(html).text();
}

That seems (very) hacky, though. What's a better way? Is there a "right" way?

1

7 Answers 7

563

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

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

Example: http://jsfiddle.net/k65s3/

Input:

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

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
26
  • 2
    Ah, seems like basically the same approach I took but without the jQuery dependency (which is nice). Doesn't it still seem hacky, though? Or should I be perfectly comfortable with it?
    – Dan Tao
    Sep 12, 2011 at 22:33
  • 41
    Oh wait, I get it: you're using textarea specifically so that the tags are preserved (as you said) but HTML entities still get decoded. Pretty clever...
    – Dan Tao
    Sep 12, 2011 at 22:34
  • 3
    It's acceptable. It's the best way to decode HTML. No tags are passed, unlike your original solution, which parse (thus hide) tags.
    – Rob W
    Sep 12, 2011 at 22:34
  • 1
    Nice trick! I'd been using a non-textarea version of this for a while, and this is by far better.
    – Domenic
    Sep 12, 2011 at 22:49
  • 1
    @Leonardo It is never attached to the document.
    – Rob W
    Sep 29, 2015 at 12:56
179

Don’t use the DOM to do this if you care about legacy compatibility. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results on non-modern browsers.

For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Here’s how you’d use it:

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

Disclaimer: I'm the author of the he library.

See this Stack Overflow answer for some more info.

7
  • 19
    I was in NodeJS so for me this was the only available solution. Jun 23, 2017 at 13:14
  • 3
    how significant "leads to differences in cross-browser results." is? In which browser the result can be very different? would you please give me exact example (which is the most significant in your mind)? I don't want to use excessive third party library, so I would like to know about it first. Dec 29, 2017 at 3:29
  • 1
    @TaufikNurRahmanda The link it points to answers that question. Jan 16, 2018 at 10:14
  • 1
    This one should be the right answer. Works better than lodash and underscore.
    – Tony Wang
    Apr 27, 2020 at 4:55
  • 11
    This library is 30KB gzipped... I don't want to get new libraries for every tiny problem I have to solve in JS. Oct 14, 2021 at 20:52
46

If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:

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);
    });
}

[Edit]

Note: this would only work for numeric html-entities, and not stuff like &oring;.

[Edit 2]

Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/

7
  • 7
    What about &amp; and other named entities? These are still not parsed in this implementation.
    – Rob W
    Sep 12, 2011 at 22:36
  • 5
    I already commented on the fact that they won't be parsed. To parse those, you'd need a hashmap of some sort (lookup). However, if this code is autogenerated (per say), then there is a chance that it always will return the numeric value. I only provided a pure-js way of doing this (works without DOM), not saying it solves the general problem, but more the specific one.
    – Alxandr
    Sep 12, 2011 at 22:45
  • 1
    Not working with &gt; &lt; Dec 23, 2016 at 13:25
  • 1
    I've just used this JSFiddle with one slight change, {1,3} to {1,4} which also allows for more characters, such as en dashes (&#8211;). For future reference, anyone else have this for other tags, such as &gt; ? Oct 15, 2017 at 23:40
  • 2
    In the regex match /(pattern)/gi the i suffix to ignore case isn't needed, as this is only going to match numbers. Along with davewoodhall's comment, I'm using /&#([0-9]{1,4});/g
    – Stephen P
    Feb 28, 2018 at 1:07
38

jQuery will encode and decode for you.

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>

3
  • 1
    For reference, any "element" will work here. There is nothing magic about the textarea that does the work here. But that said, if you're using jQuery already, I always employ this approach with fantastic results.
    – pim
    Mar 21, 2016 at 20:54
  • 10
    I would disagree. Textarea provides security which other elements, like divs, will not. If you use a div instead of a textarea, any non-encoded javascript in the input will be rendered in the browser. A textarea gets around this by treating the input as text... not as html. I haven't tried other elements to know how they behave. Mar 23, 2016 at 12:53
  • And just to further clarify: if you DO want the html to render in the browser after conversion, wrap it in an element that is not a text input.
    – Spartacus
    Jul 26, 2017 at 15:33
38

There's JS function to deal with &#xxxx styled entities:
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 = '高级程序设计';

let element = document.getElementById("testFunct");
element.innerHTML = (decodeHtmlEntity(entity));

console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
<div><span id="testFunct"></span></div>

4
  • 5
    Thank you. This function worked beautifully in a #gatsbyjs application where document could not be defined during static HTML builds. Mar 13, 2019 at 7:34
  • 3
    This is how it should be done!
    – silver
    Mar 9, 2020 at 5:42
  • 2
    This is the way! No lib cluttering, no DOM manipulation, no html injection.
    – Edeph
    Jul 23, 2021 at 11:48
  • This does not fix hex-encoding, like &#xE5; Jan 14 at 22:10
18

_.unescape does what you're looking for

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

3
  • 3
    it just replaces a few encoded characters - if you've got e.g. a &nbsp; it stays the way it is.
    – xtools
    Jan 16, 2018 at 10:41
  • e&#39 is not in the list? This only replaces &amp;, &lt;, &gt;, &quot;, &#96; and &#x27;
    – Jquestions
    Dec 14, 2018 at 11:25
  • updated link to lodash.unescape, which handles &#39
    – tldr
    Dec 15, 2018 at 16:22
0

This is so good answer. You can use this with angular like this:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);
1
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Nic3500
    Aug 29, 2018 at 16:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.