How can I convert:
from:
'\\x3c'
to:
'<';
I tried:
s=eval(s.replace("\\\\", ""));
does not work. How I do this? Thanks in advance!
Use String.fromCharCode instead of eval, and parseInt using base 16:
s=String.fromCharCode(parseInt(s.substr(2), 16));
String.fromCharCode(+("0"+s.slice(1)));String.fromCharCode("0"+s.slice(1));fromCharCode casts to an int for you! doh! :-)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;
}
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 + '"'); // => "<"
eval is unequivocally evil, but I would say that this isn't really an acceptable use of eval (since alternative options exist).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.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.