How to convert character to ASCII code using JavaScript ?

The purpose of this article is to get the ASCII code of any character by using JavaScript charCodeAt() method. This method is used to return the number indicating the Unicode value of the character at the specified index.

Syntax:

string.charCodeAt(index); 

Example: Below code illustrates that they can take character from the user and display the ASCII code of that character.

HTML Code:

HTML



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
    <h2>
        GeeksForGeeks
    </h2>
    <h2>
        How to convert character to
        ASCII code in JavaScript
    </h2>
  
    <p>
        Enter any character:
        <input type="text" id="id1" 
            name="text1" maxLength="1">
    </p>
  
    <button onclick="myFunction()">
        Get ASCII code
    </button>
  
    <p id="demo" style="color:red;">
</body>
  
</html>

chevron_right


JavaScript Code: The following code snippet illustrates the JavaScript code used in the above HTML code.

filter_none

edit
close

play_arrow

link
brightness_4
code

function myFunction() {
    var str = document.getElementById("id1");
    if (str.value == "") {
        str.focus();
        return;
    }
    var a = "ASCII Code is == >  ";
    document.getElementById("demo").innerHTML
        = a + str.value.charCodeAt(0);
}

chevron_right


Final Code: The following example is the combination of the above two code snippets.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
    <h2>
        GeeksForGeeks
    </h2>
    <h2>
        How to convert character to 
        ASCII code in JavaScript
    </h2>
  
    <script>
        function myFunction() {
            var str = document.getElementById("id1");
            if (str.value == "") {
                str.focus();
                return;
            }
            var a = "ASCII Code is == >  ";
            document.getElementById("demo").innerHTML
                = a + str.value.charCodeAt(0);
        }
    </script>
  
    <p>
        Enter any character:
        <input type="text" id="id1" 
            name="text1" maxLength="1">
    </p>
  
    <button onclick="myFunction()">
        Get ASCII code
    </button>
  
    <p id="demo" style="color:red;">
</body>
  
</html>

chevron_right


Output: