JavaScript Tutorials

JavaScript String charCodeAt()
Syntax & Examples

String.charCodeAt() method

The charCodeAt() method of the String class in JavaScript returns a number that is the UTF-16 code unit value at the given index.


Syntax of String.charCodeAt()

The syntax of String.charCodeAt() method is:

charCodeAt(index)

This charCodeAt() method of String returns a number that is the UTF-16 code unit value at the given index.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the character whose UTF-16 code unit value is to be returned.

Return Type

String.charCodeAt() returns value of type Number.



✐ Examples

1 Using charCodeAt() method to get the UTF-16 code unit value at a specific index

In JavaScript, we can use charCodeAt() method to get the UTF-16 code unit value at a specific index in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charCodeAt() method with the index 1 to retrieve the UTF-16 code unit value at that index.
  3. The code unit value at index 1, which is 101, is stored in the variable codeAtIndex1.
  4. We log codeAtIndex1 to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const codeAtIndex1 = str.charCodeAt(1);
console.log(codeAtIndex1);

Output

101

2 Using charCodeAt() method to get the UTF-16 code unit value of the last character

In JavaScript, we can use charCodeAt() method with the index str.length - 1 to get the UTF-16 code unit value of the last character in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charCodeAt() method with the index str.length - 1 to retrieve the UTF-16 code unit value of the last character.
  3. The code unit value of the last character, which is 111, is stored in the variable codeOfLastChar.
  4. We log codeOfLastChar to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const codeOfLastChar = str.charCodeAt(str.length - 1);
console.log(codeOfLastChar);

Output

111

3 Using charCodeAt() method to get the UTF-16 code unit value of the first character

In JavaScript, we can use charCodeAt() method with the index 0 to get the UTF-16 code unit value of the first character in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charCodeAt() method with the index 0 to retrieve the UTF-16 code unit value of the first character.
  3. The code unit value of the first character, which is 72, is stored in the variable codeOfFirstChar.
  4. We log codeOfFirstChar to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const codeOfFirstChar = str.charCodeAt(0);
console.log(codeOfFirstChar);

Output

72

Summary

In this JavaScript tutorial, we learned about charCodeAt() method of String: the syntax and few working examples with output and detailed explanation for each example.