Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to decode a string that has special HTML entities in it? [duplicate]

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?

like image 526
Dan Tao Avatar asked Oct 04 '22 20:10

Dan Tao


People also ask

Which method is used to decode the currently encoded HTML code?

The input string is encoded using the HtmlEncode method. The encoded string obtained is then decoded using the HtmlDecode method.

How do you decode text in HTML?

Wikipedia has a good expalanation of character encodings and how some characters should be represented in HTML. Load the HTML data to decode from a file, then press the 'Decode' button: Browse: Alternatively, type or paste in the text you want to HTML–decode, then press the 'Decode' button.

How do you decode an encoded string?

To encode a string we need encodeURIComponent() or encodeURI() and to decode a string we need decodeURIComponent() or decodeURI(). Initially, we have used escape() to encode a string but since it is deprecated we are now using encodeURI().


1 Answers

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>
like image 514
Rob W Avatar answered Oct 23 '22 16:10

Rob W