5

Essentially I want to undo the escapeHTML() function I found below, after I used it.

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

function unescapeHtml(safe) {
    return safe
         .replace("&amp;", /&/g)
         .replace("&lt;", /</g)
         .replace( "&gt;", />/g)
         .replace("&quot;", /"/g)
         .replace("&#039;", /'/g);
 }


var a = escapeHtml("<div> yo & yo squirrl's </div>");
var b = unescapeHtml(a);
console.log(a);
console.log(b);//should log "<div> yo & yo squirrl's </div>"

I tried the obvious but no deal. http://jsfiddle.net/ej6bX/

Community
  • 1
  • 1
Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • Related: http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery – Nathan Oct 06 '14 at 19:10

2 Answers2

24

You need to use

function unescapeHtml(safe) {
    return safe.replace(/&amp;/g, '&')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#039;/g, "'");
}

A more clear approach using jQuery could be

function escapeHtml(unsafe) {
    return $('<div />').text(unsafe).html()
}

function unescapeHtml(safe) {
    return $('<div />').html(safe).text();
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • That jQuery solution is pretty amazing. What is `('
    ')` for exactly? Oh I think i understand. In the situation where the string was `

    yo & yo squirrl's

    ` it would no longer work though?

    – Squirrl Mar 09 '14 at 06:56
  • 1
    @Squirrl we creates a temporary div element using `$('
    ')` then assigns the given value as text to it so that it will render the given text after doing an html escape then we reads the parsed html content which will give us the escaped string - the reverse for unescape
    – Arun P Johny Mar 09 '14 at 07:02
  • 4
    Per http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery#comment6018122_2419664, your second `unescapeHtml` is *not* secure, and can lead to XSS attacks. – Nathan Oct 06 '14 at 19:13
  • If you have a lot of calls to unescape function, then it can hurt performance - when using this approach: $('
    ')
    – Arman Bimatov Oct 21 '15 at 15:28
  • Just an improvement - instead of `/'/g`, use `/*39;/g` - because `'`, `'` (or in fact `'` or `'` etc.) all results in the same single quote. We do not know if the original encoder added any zeros or not. – Jay Dadhania Apr 18 '20 at 17:48
1

The second parameter of replace() should be string not regular expression

function unescapeHtml(safe) {
    return safe
         .replace(/&amp;/g, "&")
         .replace(/&lt;/g, "<")
         .replace(/&gt;/g, ">")
         .replace(/&quot;/g, "\"")
         .replace(/&#039;/g, "'");
 }

Fiddle

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188