Skip to content
Related Articles

Related Articles

How to convert character to ASCII code using JavaScript ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 15 Sep, 2020

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




<!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>

JavaScript Code: The following code snippet illustrates the JavaScript code used in the above HTML 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);
}

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




<!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>

Output:

  • Before Clicking on Button:

  • After Clicking On Button:

    Supported browsers:

    • Google Chrome
    • Internet Explorer
    • Firefox
    • Opera
    • Safari

    My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!