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 = "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":

  • 'c' is at index no.0
  • 'o' is at index no.1
  • 'd' is at index no.2
  • 'e' is at index no.3
  • 's' is at index no.4
  • and so on

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 = "codescracker.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 = "codescracker.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 »



Like/Share Us on Facebook 😋