JavaScript charCodeAt

Uses

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

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

Parameters

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

Return value

  • A number representing the UTF-16 code of the character at the specified index; NAN if index is out of range.

The charCodeAt() method returns the specified character from a given index of a string. If a given index out of range, charCodeAt() return NAN 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.charCodeAt(index)

Parameters

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

Example

CharAt

var myString = "Example of charCodeAt method";

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

charCodeAt Second Last index

var myString = "Example of charCodeAt method";

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

See Also