The JavaScript str.charCodeAt() method returns the Unicode code unit of the character at a given index in a string.
- Index starts from 0 to length - 1.
- Returns a number (Unicode value).
- Accepts an index as an argument.
- Used to get the numeric code of a character.
let text = "ABC";
let code = text.charCodeAt(0);
console.log(code);
Syntax:
str.charCodeAt(index)Parameters:
This method takes one parameter called index to identify a character in the string. It uses this index to work with the Unicode value of that character.
- The method accepts a single parameter: index.
- The index must be between 0 and string.length - 1.
- It refers to the position of the character whose Unicode value is used.
Return value:
This method returns a numeric value based on the character’s Unicode code. The value depends on the index you provide.
- Returns the Unicode value (between 0 and 65535) of the character.
- The value corresponds to the character at the given index.
- If the index is out of range, it returns NaN.
Example 1: This example shows the basic use of the String.prototype.charCodeAt() Method.
function func() {
let str = 'GEEKS';
let value = str.charCodeAt(0);
console.log(value);
}
func();
Example 2: In this example, the method charCodeAt() extracts the character from the string at index 4. Since this character is m, therefore this method returns the Unicode sequence as 109.
// JavaScript to illustrate charCodeAt() method
function func() {
let str = 'ephemeral';
// Finding the code of the character at
// given index
let value = str.charCodeAt(4);
console.log(value);
}
func();
Example 3: In this example, the method charCodeAt() extracts the character from the string at index 20. Since the index is out of bounds for the string, therefore this method returns the answer as NaN.Â
// JavaScript to illustrate charCodeAt() method
function func() {
let str = 'ephemeral';
// Finding the code of the character
// at given index
let value = str.charCodeAt(20);
console.log(value);
}
func();
Supported Browsers:
- Chrome 1
- Edge 12
- Firefox 1
- safari 1
- Opera 4