1

I've got a single dependency on jQuery that I don't want, and need a browser-safe method to decode server-side html encoded content.

The effect I'm going for is to replace an existing DOM element with the the html that gets decoded, along the following lines:

$('#targetId').replaceWith($('<div/>').html(value).text());

where value contains an html-encoded string.

Alternatively, an more direct approach would also be welcome.

Ryan Weir
  • 6,377
  • 5
  • 40
  • 60
  • possible duplicate of [How to decode HTML entities using jQuery?](http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery) – kapa Feb 13 '14 at 22:34
  • 4
    @kapa - not a duplicate. OP is asking to do this without jquery. – mayabelle Feb 13 '14 at 22:36
  • 1
    @mayabelle Yeah, did not notice. Sorry. In this case: http://css-tricks.com/snippets/javascript/unescape-html-in-js/ – kapa Feb 13 '14 at 22:37

2 Answers2

1

Here's one way to do it:

function DecodeHtmlString(htmlString){
  var temp = document.createElement("textarea");
  temp.innerHTML = htmlString;
  return temp.value;
}
mayabelle
  • 9,804
  • 9
  • 36
  • 59
0

Real world alternative. I mix some PHP because reasons.

var Lang = Lang || new Object();

Lang._t  = function(str) {
    var buf = [];

    for (var i=str.length-1;i>=0;i--) {
        buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
    }

    return buf.join('');
},


Lang.same_password = Lang._t(<?php echo json_encode($langtextos->same_password); ?>);


function foo(pass1, pass2){
   if( pass1 == pass2){
       message.innerHTML = Lang.same_pass;
       return false;
   }
      
   return true;
}
CodeNinja
  • 9
  • 1