The charCodeAt() method of the String class in JavaScript returns a number that is the UTF-16 code unit value at the given index.
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.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the character whose UTF-16 code unit value is to be returned. |
String.charCodeAt() returns value of type Number
.
In JavaScript, we can use charCodeAt()
method to get the UTF-16 code unit value at a specific index in the string.
For example,
str
with the value 'Hello'
.charCodeAt()
method with the index 1
to retrieve the UTF-16 code unit value at that index.1
, which is 101
, is stored in the variable codeAtIndex1
.codeAtIndex1
to the console using console.log()
method.const str = 'Hello';
const codeAtIndex1 = str.charCodeAt(1);
console.log(codeAtIndex1);
101
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,
str
with the value 'Hello'
.charCodeAt()
method with the index str.length - 1
to retrieve the UTF-16 code unit value of the last character.111
, is stored in the variable codeOfLastChar
.codeOfLastChar
to the console using console.log()
method.const str = 'Hello';
const codeOfLastChar = str.charCodeAt(str.length - 1);
console.log(codeOfLastChar);
111
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,
str
with the value 'Hello'
.charCodeAt()
method with the index 0
to retrieve the UTF-16 code unit value of the first character.72
, is stored in the variable codeOfFirstChar
.codeOfFirstChar
to the console using console.log()
method.const str = 'Hello';
const codeOfFirstChar = str.charCodeAt(0);
console.log(codeOfFirstChar);
72
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.