JavaScript charCodeAt

The JavaScript charCodeAt function returns the Unicode of the Character at a specified index position. The syntax of the function is

String_Object.charCodeAt(Index_Position)

The JavaScript charCodeAt Function returns the Character Unicode from String_Object at the specified Index_Position. If we specify the Index position out of range, then it returns NaN.

JavaScript CharCodeAt Example

The set of examples to understand the CharCodeAt Function. The first statement finds the Character Unicode at index position 9, which will be G. Remember, you should count the space as One Character.

In the next line, we use the JavaScript len function to calculate the string length. In this statement, we are subtracting 1 from string length. Because the length of a Str_Original is 16, and there is no character at index position 16.

Let us see what will happen when we select 16 in charCodeAt. It returns NaN.

<!DOCTYPE html>
<html>
<head>
    <title>JavaScriptCharCodeAt</title>
</head>
<body>
    <h1>JavaScriptCharCodeAt</h1>
    <p id= "Content1">Content 1</p>
    <p id= "Content2">Content 3</p>
    <p id= "Content3">Content 2</p>
<script>
 var Str_Original = "Tutorial GateWay";
 var Str_Extracted = Str_Original.charCodeAt(9);
 var Str_Extracted1 = Str_Original.charCodeAt(Str_Original.length - 1);
 var Str_Extracted2 = Str_Original.charCodeAt(Str_Original.length);
    
 document.getElementById("Content1").innerHTML = "Charcter at Index position 9 = " + Str_Extracted;
 document.getElementById("Content2").innerHTML = "Charcter at Index position 15 = " + Str_Extracted1; 
 document.getElementById("Content3").innerHTML = "Charcter at Index position 16 = " + Str_Extracted2; 
</script>
</body>
</html>
JavaScript CharCodeAt Function Example