JavaScript String charCodeAt() Method

JavaScript String charCodeAt() method returns the Unicode value of the character at the specified index(position) in the string. The index of the last character is string length – 1.

Syntax

string.charCodeAt(index)

Parameters

index(optional): A number representing the index of the character you want to return. (Default 0)

Return value

Returns an integer between 0 and 65535 representing the UTF-16 code unit at the specific index or NaN if there is no character at the specific index(or if the index is less than 0.)

Visual RepresentationVisual Representation of JavaScript String charCodeAt() Method

Example 1: How to Use String charCodeAt() Function

The UTF-16 code unit matches a Unicode code point for code points described in the single UTF-16 code unit.

If a Unicode code point cannot be represented in the single UTF-16 code unit (because its value is greater than 0xFFFF), then the coding unit returned will be the first part of a surrogate pair for the code point.

let str = "AppDividend"; 
unicodeValue = str.charCodeAt(7); 
console.log(unicodeValue);

Output

100

Example 2: Passing no parameterVisual Representation of Passing no parameter

let str = "AppDividend"; 
unicodeValue = str.charCodeAt(); 
console.log(unicodeValue);

Output

65

Example 3: When the index value is out of range Visual Representation of When the index value is out of range in the charCodeAt() method

let str = "AppDividend"; 
unicodeValue = str.charCodeAt(17); 
console.log(unicodeValue);

Output

NaN

In the above example, it returns a NaN because the index is out of range.

Example 4: Passing the length of a string as an argument

let str = "AppDividend"; 
unicodeValue = str.charCodeAt(str.length);
console.log(unicodeValue);

Output

NaN

Browser compatibility

  1. Chrome 1 and above
  2. Edge 12 and above
  3. Firefox 1 and above
  4. Safari 1 and above
  5. Opera 4 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.