JavaScript charAt()

The JavaScript charAt() method is used when we need to find a character available at a specified position in a specified string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>The character at index no.4 is: <span id="x"></span></p>

   <script>
      let myString = "codescracker.com";
      
      let myChar = myString.charAt(4);
      document.getElementById("x").innerHTML = myChar;
   </script>
   
</body>
</html>
Output

The character at index no.4 is:

Since indexing starts with 0, therefore, in the string "codescracker.com":

JavaScript charAt() syntax

The syntax of the charAt() method in JavaScript is:

string.charAt(index)

The index parameter is optional. Its default value is 0. Therefore, without an index parameter, the charAt() method returns the first character of the specified string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      let myStr = "codescracker.com";
      document.getElementById("xyz").innerHTML = myStr.charAt();
   </script>
   
</body>
</html>
Output

Find the last character of a string using charAt()

To find the last character of a specified string using the charAt() method in JavaScript, here is an example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      let mstr = "codescracker.com";
      document.getElementById("abc").innerHTML = mstr.charAt(mstr.length - 1);
   </script>
   
</body>
</html>
Output

Note: The string.length property returns the length of the string.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!