4

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

I tried:

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

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

3 Answers 3

12

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

s=String.fromCharCode(parseInt(s.substr(2), 16));
3
  • 1
    +1, a shorter alternative would be String.fromCharCode(+("0"+s.slice(1)));
    – Andy E
    Commented Aug 24, 2011 at 15:59
  • @Andy Even shorter: String.fromCharCode("0"+s.slice(1)); Commented Aug 25, 2011 at 6:55
  • @DigitalPlane: of course, fromCharCode casts to an int for you! doh! :-)
    – Andy E
    Commented Aug 25, 2011 at 8:35
1

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;
}
0
0

One way to do it, which will incur the wrath of people who believe that "eval" is unequivocally evil, is as follows:

var s = "\\x3c";
var s2 = eval('"' + s + '"'); // => "<"
3
  • 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).
    – Andy E
    Commented Aug 24, 2011 at 16:08
  • @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.
    – maerics
    Commented Aug 24, 2011 at 16:47
  • 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.
    – Andy E
    Commented Aug 25, 2011 at 0:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.