The character at a specified position within a string, can be returned using the charAt() string method.
The following code example is a simple demonstration of the charAt() method.
var MyString = 'Some Text';
var Index = 2;
var MyCharacter = MyText.charAt(Index);
document.write(MyCharacter);
In this case, the lowercase letter “m” will be printed to the document because it has an index value if 2.
The Valid Range of Values Passed to the charAt() Method
Tip: It is important to remember that index values are always counted by starting with zero, not one.
The minimum value will always be zero, and the value of the index can not be negative.
The maximum value that can be returned by the charAt() method is always the length of the string minus one.
If charAt() is passed a value that is equal to or greater than the length of the string, it will not return a value, and no error will not be generated even when using strict mode.
This can lead to situations that are difficult to debug, so it is recommended that the index value is compared to the length of the string to avoid problems.
In the following example, if the value of the index variable is greater than or equal to the length of the MyString variable, then a helpful error message is printed to the console.
if (Index >= MyString.length || Index < 0)
{
console.log("The Index is out of Bounds.");
}
Note: There is a strange occurrence when the string is empty and the value of the index is zero. In this case, the index is out of bounds because there is no range of characters that can be returned by the charAt() method.
The Array Method Alternative
Another way to retrieve a single character from a string is to use square brackets.
var MyString = 'Some Text';
var Index = 2;
var MyCharacter = MyText[Index];
document.write(MyCharacter);
This code is functionally identical to the previous example. The only difference is that the array method is compatible with slightly fewer browsers. The array method is also not recommended because the code is slightly harder to comprehend.
The charAt() Method Does Not Work on a Number
If you want to use this method on a number, you must first convert it to a string.
var MyNumber = 89;
//document.write(MyNumber.charAt(1));
//produces the error: .charAt is not a function
//working:
var MyString = MyNumber.toString();
document.write(MyString.charAt(1));
The charAt() Method Can be Passed Invalid Values as Arguments
Many JavaScript methods are quite quirky and can be passed values that are not valid, but do not produce any errors or warnings, even when using the strict mode.
The following examples do nothing:
var MyText = "Sample Text";
//passing no value to charAt() does nothing
document.write(MyText.charAt());
//passing a string to charAt() also does nothing
document.write(MyText.charAt("test")