4

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

I tried:

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

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

maerics
  • 151,642
  • 46
  • 269
  • 291
Jack
  • 16,276
  • 55
  • 159
  • 284

3 Answers3

12

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

s=String.fromCharCode(parseInt(s.substr(2), 16));
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
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;
}
Community
  • 1
  • 1
Mrchief
  • 75,126
  • 20
  • 142
  • 189
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 + '"'); // => "<"
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 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 Aug 24 '11 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 Aug 24 '11 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 Aug 25 '11 at 00:36