JavaScript charCodeAt() is used to get a Unicode value for a character at a specific position in a string. This method returns an integer between 0
and 65535
representing the UTF-16 code unit at the given index.
string.charCodeAt(index)
Note: If index is out of range, charCodeAt() returns NaN.
The following example returns 65
, the Unicode value for A.
'ABC'.charCodeAt(0) // returns 65
JavaScript charCodeAt example
A simple example code gets the Unicode of the first character in a string. Where the index of the first character is 0, the second is 1.
<!DOCTYPE html>
<html>
<body>
<script>
let text = "HELLO WORLD";
let code = text.charCodeAt(0);
console.log(code)
</script>
</body>
</html>
Output:
Get the Unicode of the last character in a string:
<script>
let text = "HELLO WORLD";
let code = text.charCodeAt(text.length-1);
console.log(code)
</script>
Do comment if you have any doubts or suggestions on this JS essential function.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
how can the result be 72?
It’s 72 because that’s the Utf 16 value for ‘H’ . The character at position 0 in ‘Hello World’