Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode HTML with Javascript [duplicate]

I am trying to pull data from a data attribute of a link and decode the HTML in it, but it is not working.

Here is a JSFiddle of my code: http://jsfiddle.net/Kd25m/1/

HTML:

<a id="main" class="margin-right-5 no-underline" href="#" data-qid="0" data-name="Post\u0026#39;\u0026#39; \u0026#39;!@#$%^\u0026amp;*()_+{}|:\u0026quot;\u0026lt;\u0026gt;?,./;\u0026#39;[]\\212\u0026quot;\u0026quot;3\u0026quot;4567890-=\u0026#39;" data-caption="" data-description="Animals are generally considered to have evolved from a flagellated eukaryote.[39] \u0026#39;!@#$%^\u0026amp;*()_+{}|:\u0026quot;\u0026lt;\u0026gt;?,./;\u0026#39;[]\\21234567890-=\u0026#39;Their closest known living relatives are the ch...">
Alert Decoded HTML</a>

JS:

$('#main').click(function(e){
    e.preventDefault()
    //alert("AA");
    var name = $('#main').data('name');
    alert(name);
    var decoded = $("<div/>").html(name).text();
    alert(decoded);
});

Using this works if a string is put in the name var, but if I pull the value from the data attribute, it doesn't work anymore.

like image 540
user3072169 Avatar asked Sep 05 '26 19:09

user3072169


1 Answers

Try to unescape the unicode characters first:

function convert(str){

    return str.replace(/\\u([a-f0-9]{4})/gi, function (found, code) {
      return String.fromCharCode(parseInt(code, 16));
    });

}

Next try to make the div and html trick:

var decoded = $("<div/>").html(convert(name)).text();
like image 184
ElChiniNet Avatar answered Sep 07 '26 08:09

ElChiniNet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!