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
Parameter | Optional/Required | Description |
---|---|---|
index | required | The 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,
- We define a string variable
str
with the value'Hello'
. - We use the
charCodeAt()
method with the index1
to retrieve the UTF-16 code unit value at that index. - The code unit value at index
1
, which is101
, is stored in the variablecodeAtIndex1
. - We log
codeAtIndex1
to the console usingconsole.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,
- We define a string variable
str
with the value'Hello'
. - We use the
charCodeAt()
method with the indexstr.length - 1
to retrieve the UTF-16 code unit value of the last character. - The code unit value of the last character, which is
111
, is stored in the variablecodeOfLastChar
. - We log
codeOfLastChar
to the console usingconsole.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,
- We define a string variable
str
with the value'Hello'
. - We use the
charCodeAt()
method with the index0
to retrieve the UTF-16 code unit value of the first character. - The code unit value of the first character, which is
72
, is stored in the variablecodeOfFirstChar
. - We log
codeOfFirstChar
to the console usingconsole.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.