The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method.
The charCodeAt method can be used with both standard strings defined with single or double quotes and String objects or literal templates.
In this example we get the Unicode codes of the characters in position 1 of the string 'JavaScript':
const codetest = 'JavaScript'.charCodeAt(0) // 74 const codetest = 'JavaScript'.charCodeAt(1) // 97
If there is no character in the position we pass as parameter to the method, the returned value will be NaN. This case will occur when we want to obtain the code of the character that is in a position whose value is equal to or greater than the length of the string. The NaN value means Not a Number, returned when the result obtained is not a numeric value.
In this example we get the Unicode code of the character at position 20 of the string 'JavaScript':
In the following example we get the Unicode code of the character at position 20 of the string 'JavaScript':
const codetest = 'JavaScript'.charCodeAt(20) // NaN
The charCodeAt method works in exactly the same way with String objects, as you can see in the following example
const chain = new String('JavaScript'); const codetest = chain.charCodeAt(1); // 97
The charCodeAt method, like all methods commonly used with strings in JavaScript, is case sensitive. Therefore, the character A is considered different from the character a.
In addition, you can use the toString method with the result obtained by the charCodeAt method to convert the Unicode code into a character.
In case you want to get the representation of special characters whose representation consists of two 16-bit units, you have to use the charCodeAt method twice, with two consecutive indices. Alternatively, you can also use the codePointAt method. Alternatively, you can also use the codePointAt method. For more information about this method, see how to use the codePointAt method in JavaScript.
Read also: