11

How do i unescape HTML Entities in JS?

When googling i literally saw answers with a huge switch and people rolling their own.

I'd like the string &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt; to become <html xmlns="http://www.w3.org/1999/xhtml" >

  • Accepted answer has security issues ([read more here](https://stackoverflow.com/a/1395954/6476044)). To avoid XSS vulnerability you should use [he library](https://github.com/mathiasbynens/he). You can see code examples in [answer to similar question](https://stackoverflow.com/a/23596964/6476044). – ands Oct 24 '19 at 20:25

2 Answers2

17

Create a div, set it's innerHTML and then read innerText

var d = document.createElement("div");
d.innerHTML = "&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;";
alert(d.innerText || d.text || d.textContent);
Sky Sanders
  • 36,396
  • 8
  • 69
  • 90
  • That code doesnt work but this does http://jsfiddle.net/gHHzA/ –  Dec 18 '10 at 23:52
  • @acid - likely a cross browser issue. will update for others. – Sky Sanders Dec 19 '10 at 00:48
  • 1
    Sky Sanders: Odd, i tried it on all installed browsers (ie8, opera, safari, chrome) and it worked except for my main browser firefox 3.6. It turns out FF uses d.textContent (i found it via firebug) http://jsfiddle.net/P3DPy/1/ –  Dec 19 '10 at 04:27
  • 2
    @acid lolz. thanks. update should work across the board now. – Sky Sanders Dec 19 '10 at 05:50
  • Just to point out, empty string is false-y, so passing '' to this would return undefined in any browser where the last expression is undefined, because it'll fall through to there when all other tests fail. The jQuery/Sizzle implementation of elem.text() is non-trivial if elem.textContent isn't supported by the browser, so a correct implementation has to either use a framework, explicitly check for empty string, or return something like this: (typeof d.textContent === 'string') ? d.textContent : (typeof d.innerText === 'string') ? d.innerText : d.text. Messy. – enigment Aug 10 '15 at 20:58
2

Here is a JS implementation of a PHP function that decodes HTML entities

http://phpjs.org/functions/html_entity_decode

Note that this function also depends on:

http://phpjs.org/functions/get_html_translation_table

Samuel
  • 16,923
  • 6
  • 62
  • 75