The JavaScript CharAt method returns the character at a specified index position. The index position will start from 0, Not 1. Let me show you the syntax of the CharAt function is as shown below.
String_Object.CharAt(Index_Position)
This string function accepts a single parameter and returns the Character from the String_Object at the specified Index_Position. If we specify an index position out of range, the ChartAt Function returns an empty string.
TIP: To get the Unicode of a character, use the charCodeAt() method, and to return the index position of a character, use indexOf().
JavaScript CharAt Example
The following set of examples will help you understand the CharAt Function. The first statement will find the Character at index position 9, which will be G. Remember, the charat function counts the space as One Character.
In the next line, we use the JavaScript len function to calculate the string length. Here, we are subtracting one from the string length because the length of a Str_Original is 16, and there is no character in the index position 16.
In the next line, we show you the result when we choose the index position as 16. This JavaScript Character At statement returns the empty string. Finally, the document getElementById statements will place the content in the respective paragraphs.
NOTE: Use the substring() function to get the substring or the slice() to returns group of characters within a range.
<!DOCTYPE html>
<html>
<head>
<title>JavaScriptCharAt</title>
</head>
<body>
<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.charAt(9);
var Str_Extracted1 = Str_Original.charAt(Str_Original.length - 1);
var Str_Extracted2 = Str_Original.charAt(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;
document.write("Charcter at Index position 9 = " + Str_Extracted);
</script>
</body>
</html>
