23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 2 ■ TYPE CONVERSION<br />

32<br />

Decoding or Encoding Characters<br />

For nonkeyboard characters, it’s typically simpler to work with the Unicode encoding than the<br />

character. For example, Dr. Otto Günther Octavius is the secret identity of one of Spider-Man’s<br />

archenemies, Doctor Octopus. Rather than try to type the ü in Günther, pass its Unicode encoding (252)<br />

to String.fromCharCode() like so in Firebug, verifying your work with Figure 2–7:<br />

var id = "Dr. Otto G" + String.fromCharCode(252) + "nther Octavius";<br />

id;<br />

// "Dr. Otto Günther Octavius"<br />

Figure 2–7. String.fromCharCode() provides a way to insert nonkeyboard characters.<br />

Conversely, it’s simpler to encode the ü and work with 252, say in a comparison, than to try to type<br />

the ü. To do so, pass the index to charCodeAt(), which returns the Unicode encoding rather than the<br />

character, as its partner in crime, charAt(), would. Although the following two comparisons are<br />

equivalent, I’m guessing you were only able to key in the first in Firebug. Figure 2–8 displays both,<br />

however.<br />

var id = "Dr. Otto G" + String.fromCharCode(252) + "nther Octavius";<br />

id.charCodeAt(10) === 252;<br />

// true<br />

id.charAt(10) === "ü";<br />

// true

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!