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 Representation
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 parameter
let str = "AppDividend";
unicodeValue = str.charCodeAt();
console.log(unicodeValue);
Output
65
Example 3: When the index value is out of range
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
- Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Safari 1 and above
- Opera 4 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.