Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:String:charAt

From MDC


Contents

[edit] Summary

Returns the specified character from a string.

Method of String
Implemented in: JavaScript 1.0, NES2.0
ECMA Version: ECMA-262

[edit] Syntax

charAt(index)

[edit] Parameters

index 
An integer between 0 and 1 less than the length of the string.

[edit] Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

[edit] Examples

[edit] Example: Displaying characters at different locations in a string

The following example displays characters at different locations in the string "Brave new world":

var anyString="Brave new world"

document.writeln("The character at index 0 is '" + anyString.charAt(0) + "'")
document.writeln("The character at index 1 is '" + anyString.charAt(1) + "'")
document.writeln("The character at index 2 is '" + anyString.charAt(2) + "'")
document.writeln("The character at index 3 is '" + anyString.charAt(3) + "'")
document.writeln("The character at index 4 is '" + anyString.charAt(4) + "'")
document.writeln("The character at index 999 is '" + anyString.charAt(999) + "'")

These lines display the following:

The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''

[edit] See Also

indexOf, lastIndexOf, split, charCodeAt