Learning by exploring
June 14th, 2011To learn a language by heart, try to set some time aside to explore it! Set yourself a specific goal—for example, find three ways to convert a character code to a string in JavaScript.
Here’s the basic set up, with what probably makes the most sense in almost any situation.
var charCode = 65; String.fromCharCode(charCode) // => "A"
Where to go from here? It seems, at first that there is no other way to achieve this, right? Wrong, of course.
As a scripting language, JavaScript has powerful ways to evaluate generated code. Let’s try using the eval
function to do this. Remember that JavaScript strings can contain escape sequences, for example in the form of xAB
, where AB is a hexadecimal character code:
eval("'\x"+charCode.toString(16)+"'") // => "A"
An here’s a third way to do it, using the unescape DOM method:
unescape('%'+charCode.toString(16)) // => "A"
There are even more possible ways to achieve this conversion—try to find one!
Tweet