The charCodeAt function in JavaScript is employed to determine the Unicode value of a character located at a particular index within a string.
The index in a string begins at 0 and extends to n-1, with n representing the string's length. If the specified index is negative or equal to or exceeds the string's length, the function will return NaN.
Syntax
The method charCodeAt is denoted by the syntax below:
string.charCodeAt(index)
Parameter
index - It represent the position of a character.
Return
A Unicode value
JavaScript String charCodeAt Method Example
Let's explore a few basic illustrations showcasing the functionality of the charCodeAt method.
Example 1
In this section, we'll demonstrate how to display the Unicode value of a character by providing its corresponding index.
<script>
var x="Example";
document.writeln(x.charCodeAt(3));
</script>
Output:
Example 2
In this instance, we will demonstrate omitting the index number in the method call. In this scenario, the method will return the Unicode value of the initial character.
<script>
var x="Example";
document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
</script>
Output:
Example 3
In this section, we will display the Unicode value of the final character within a given string.
<script>
var x="Example";
document.writeln(x.charCodeAt(x.length-1));
</script>
Output:
Example 4
In this section, we will discuss scenarios where the index value exceeds the length of the string. When this situation occurs, the function will output NaN.
<script>
var x="Example";
document.writeln(x.charCodeAt(12));
</script>
Output: