JavaScript charAt

Use

var str = "Hello Reader";
var result = str.charAt(6);  // str.charAt(index);

// result
console.log(result); // Output will be R

Parameters

  • index: An number between 0 and (the length of the string – 1), Default will be zero, If no index is provided, charAt() will use 0

Return value

  • The character at the specified index of given string; empty string if index is out of range.

The charAt() method returns the specified character from a given index of a string. If a given index out of range, charAt() return empty string.

The index start with zero and last index is str.length - 1

The other way (introduced in ECMAScript 5) to access a character is to treat the string as an array, where individual character is a numerical index: str[index]

Syntax

string.charAt(index)

Parameters

index: A number between 0 and (the length of the string – 1), Default will be zero, If no index is provided, charAt() will use 0

Example

CharAt

var myString = "Example of chatAt method";

console.log("The character at last index ", myString.charAt(myString.length-1));
console.log("The character at first index ", myString.charAt());
console.log("The character at first index ", myString.charAt(0));
console.log("The character at second index ", myString.charAt(1));

CharAt Second Last index

var myString = "Example of chatAt method";

console.log(myString.charAt(myString.length-2));  // Output will be :- o

See Also