JavaScript charAt() Method
This tutorial introduces the charAt() method, from the JavaScript String object. The charAt() method is used to retrieve the character from a string, and takes an integer argument representing the position index of the character to extract.
Related string method:
Unlike the charAt() method, the charCodeAt() method is used to retrieve the Unicode character code equivalent to the actual character extracted.
Using the charAt() Method
The charAt() method can be applied on any valid JavaScript string, and used to return a character at the position index supplied. Often, however, charAt() is most useful to iterate through characters in a string — whatever the purpose.
var carter = new String("I learn JavaScript.");
// Extract first and second characters with charAt()
// Separate results with new line character
alert ( carter.charAt(0) +"\n"+ carter.charAt(1) );
The script above first declares a JavaScript string, and assigns it a value. The alert() method then displays the result returned by our calls to charAt() on our string's first and second character:
The first character, "I", is clearly visible; the second character is not, because the charAt() method returned the space between our string's first and second word.
Like arrays, JavaScript strings use a zero-based index: this means that the first character of any string actually occupies the positional index 0 (zero). The second character has position index 1.
See the String length property tutorial for details.
Variable Arguments for charAt() Method
While the charAt() method accepts plain integers as arguments, you can also pass variables with integer values. The script below returns the last character of a string, using the length property of strings:
var carter = new String("I learn JavaScript.");
// Use string length property to extract the last character
alert( carter.charAt( carter.length-1 ) );
Our JavaScript code indeed returned a period, the last character in our string:
JavaScript's charAt(), substr(), and substring() Methods
The JavaScript string objects includes three methods that allow you to extract substrings of text: the charAt() method (for a single character), the substr() method (fixed start index and relative length), and the substring() method (for a fixed start and end index positions).
The script below how to obtain the same result from each of the three methods:
var carter = "I learn JavaScript.";
// Let's extract the "J" in "JavaScript"
var outCode;
outCode = carter.charAt(8) +"\n";
outCode += carter.substr(8,1) +"\n";
outCode += carter.substring(8,9);
alert( outCode );
After storing the results, separated by a new line character, the last line of code produces the following result:
Test the charAt() Method
Interactively test the charAt() method by editing the JavaScript code below and clicking the Test charAt() Method button.
Browser support for JavaScript charAt() method | |||
---|---|---|---|