HTML Entity Decode [duplicate]

  1. Home
  2. javascript
  3. HTML Entity Decode [duplicate]

This question already has an answer here:

How do I encode and decode HTML entities using JavaScript or JQuery?

var varTitle = "Chris' corner";

I want it to be:

var varTitle = "Chris' corner";

First answer

You could try something like:

var Title = $('<textarea />').html("Chris&apos; corner").text();
<script src=""></script>

JS Fiddle.

A more interactive version:

$('form').submit(function() {
  var theString = $('#string').val();
  var varTitle = $('<textarea />').html(theString).text();
  return false;
<script src=""></script>
<form action="#" method="post">
    <label for="string">Enter a html-encoded string to decode</label>
    <input type="text" name="string" id="string" />
    <input type="submit" value="decode" />

<div id="output"></div>

JS Fiddle.

Second answer

Like Robert K said, don’t use jQuery.html().text() to decode html entities as it’s unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.

Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:


Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"


The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, ` and ' with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.

Third answer

Here’s a quick method that doesn’t require creating a div, and decodes the “most common” HTML escaped chars:

function decodeHTMLEntities(text) {
    var entities = [
        ['amp', '&'],
        ['apos', '\''],
        ['#x27', '\''],
        ['#x2F', '/'],
        ['#39', '\''],
        ['#47', '/'],
        ['lt', '<'],
        ['gt', '>'],
        ['nbsp', ' '],
        ['quot', '"']

    for (var i = 0, max = entities.length; i < max; ++i) 
        text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);

    return text;
Spread the love

Related articles

Comments are closed.