JavaScript charCodeAt() Method
This tutorial covers JavaScript's charCodeAt() method, part of the String object. The charCodeAt() method is applied on a string, and returns the decimal Unicode value corresponding to the character at the position index passed as argument.
Related string method:
Unlike the charCodeAt() method, the charAt() method retrieves the actual character found at the position index supplied (rather than its Unicode value).
Using the charCodeAt() Method
The JavaScript code below declares a string, and extract the decimal Unicode value corresponding to the character extracted; for illustration purposes, we will use charCodeAt() in conjunction with charAt().
var carter = "I learn JavaScript (javascript)";
var outCode = new String();
// UPPERCASE J
outCode = carter.charAt(8) +" ... "+ carter.charCodeAt(8) + "\n";
// lowercase j
outCode += carter.charAt(20) +" ... "+ carter.charCodeAt(20);
alert( outCode );
Explanations: we first stored the character at position index 8 (uppercase "J"), and its decimal Unicode value returned by charCodeAt(). We then did the same for lowercase "j". The purpose was to illustrate that a letter has a different decimal Unicode value depending on capitalization.
The Unicode character set includes all ASCII characters; in fact, the decimal values of Unicode characters are the same as ASCII for the letters, numbers, and a few other characters. You will probably come across these terms used interchangeably.
Determining Decimal Unicode Values with Single-Character Strings
You can easily determine which decimal Unicode corresponds to a certain character by calling the charCodeAt() method on an anonymous, single-character string:
alert( "A".charCodeAt(0) );
This one-line script produces the result below — do not omit the joining period between the anonymous string and the charCodeAt() method.
Test the charCodeAt() Method
Interactively test the charCodeAt() method by editing the JavaScript code below and clicking the Test charCodeAt() Method button.
Browser support for JavaScript charCodeAt() method | |||
---|---|---|---|