revision:
The charAt() method returns the character at a specified index (position) in a string. The index of the first character is 0, the second 1, ...
string.charAt(index)
Parameters:
index : optional. The index (position) of the character to be returned. Default is 0.
<p>charAt() returns the character at a specified index (position) in a string.</p> <p>Get the first character in a string:</p> <p id="demo"></p> <script> let text = "HELLO WORLD"; let letter = text.charAt(0); document.getElementById("demo").innerHTML = letter; </script>
<div> <p id="at-1"></p> <p id="at-2"></p> <p id="at-3"></p> <p id="at-4"></p> <p id="at-5"></p> <p id="at-6"></p> <p id="at-7"></p> </div> <script> let text = "HELLO WORLD"; document.getElementById("at-1").innerHTML = "string : " + text; let letter = text.charAt(1); document.getElementById("at-2").innerHTML = "second letter : " + letter; let letter1 = text[1]; document.getElementById("at-3").innerHTML = "second letter : " + letter1; let letter2 = text.charAt(text.length-1); document.getElementById("at-4").innerHTML = "last letter : " + letter2; let letter3 = text.charAt(15); document.getElementById("at-5").innerHTML = "index out of range : " + letter3; let letter4 = text.charAt(); document.getElementById("at-6").innerHTML = "letter : " + letter4; let letter5 = text.charAt(3.14); document.getElementById("at-7").innerHTML = "invalid index : " + letter5; </script>