JavaScript charCodeAt(): Find the Unicode of a Character at a Specified Index

The JavaScript charCodeAt() method is used when we need to find the Unicode of a character at a specified index in a specified string. For example:

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

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

The Unicode of the character at index no.4 is:

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

Because the Unicode value of s (which is at index no. 4) is 115, you are seeing 115 on the output produced above.

JavaScript charCodeAt() syntax

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

string.charCodeAt(index)

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

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

   <p id="xyz"></p>

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

In the above example, the following JavaScript statement:

let myStr = "codescracker.com";

declares a variable myStr and assigns it the value of the string "codescracker.com". And the following JavaScript statement:

document.getElementById("xyz").innerHTML = myStr.charCodeAt();

uses the getElementById method to retrieve the paragraph element with the id of "xyz". It then sets the innerHTML property of that element to the result of calling the charCodeAt() method on myStr. Since no index is specified, it returns the Unicode value of the first character in myStr, which is 99 (the Unicode value for the letter "c"). This means that the contents of the paragraph element will be "99".

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!