JavaScript charAt() | Find Character at Specified Position in String

The JavaScript charAt() method is used when we need to find character available at 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 = "jobails.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 "jobails.com":

JavaScript charAt() Syntax

The syntax of charAt() method in JavaScript is:

string.charAt(index)

The index parameter is optional. Its default value is 0. Therefore, without 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 = "jobails.com";
      document.getElementById("xyz").innerHTML = myStr.charAt();
   </script>
   
</body>
</html>
Output

Find 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 = "jobails.com";
      document.getElementById("abc").innerHTML = mstr.charAt(mstr.length - 1);
   </script>
   
</body>
</html>
Output

Note - The string.length returns the length of the string.

JavaScript Online Test


« Previous Tutorial Next Tutorial »