hex to string in javascript

12,548

Solution 1

Use String.fromCharCode instead of eval, and parseInt using base 16:

s=String.fromCharCode(parseInt(s.substr(2), 16));

Solution 2

If you're using jQuery, try this: $('<div>').html('\x3c').text()

Else (taken from here)

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Share:
12,548
Jack
Author by

Jack

Computer lover. :-) -- I'm not a native speaker of the english language. So, if you find any mistake what I have written, you are free to fix for me or tell me on. :)

Updated on June 04, 2022

Comments

  • Jack
    Jack almost 2 years

    How can I convert: from: '\\x3c' to: '<';

    I tried:

    s=eval(s.replace("\\\\", "")); 
    

    does not work. How I do this? Thanks in advance!

  • Andy E
    Andy E over 12 years
    +1, a shorter alternative would be String.fromCharCode(+("0"+s.slice(1)));
  • Andy E
    Andy E over 12 years
    I wouldn't say eval is unequivocally evil, but I would say that this isn't really an acceptable use of eval (since alternative options exist).
  • maerics
    maerics over 12 years
    @Andy E: ok, I'll take the bait =) I agree the String.fromCharCode is the right way but assuming we have validated the input (e.g. ensured it can only be an escaped character reference) then what's the potential harm in using eval here? To me it seems like one of the few times where it is ok.
  • Andy E
    Andy E over 12 years
    I wasn't fishing ;-) But since you asked, eval is not only avoided for its security risks when passed unsanitised values, but also for its poor performance. Although eval itself is slow (since it invokes the js compiler), it also makes the code around it slow. The reason for this is, where a compiler would normally make optimizations as it interprets code, it cannot know the result of the eval'd expression and therefore cannot make such optimizations. There are uses for eval, but in the end it's the dev's decision to look at alternative solutions before taking the plunge.
  • Digital Plane
    Digital Plane over 12 years
    @Andy Even shorter: String.fromCharCode("0"+s.slice(1));
  • Andy E
    Andy E over 12 years
    @DigitalPlane: of course, fromCharCode casts to an int for you! doh! :-)