This question already has an answer here:
- Unescape HTML entities in Javascript? 10 answers
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?
This is so good answer. You can use this with angular like this:
If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:
[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/
There's JS function to deal with &#xxxx styled entities:
function at GitHub
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
Example: http://jsfiddle.net/k65s3/
Input:
Output:
_.unescape
does what you're looking forhttps://lodash.com/docs/#unescape
Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.
For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:
Here’s how you’d use it:
Disclaimer: I'm the author of the he library.
See this Stack Overflow answer for some more info.