JavaScript - charCodeAt() method

revision:


Category : string

The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string.The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1.

Syntax :

        string.charCodeAt(index)    
    

Parameters:

index : optional. A number. The index (position) of the character to be returned. Default is 0.

Examples:

        <p>charCodeAt() returns the Unicode of the character at a specified position in a string.</p>
        <p>Get the Unicode of the first character:</p>
        <p id="demo"></p>
        <script>
            let text = "HELLO WORLD";
            let letter = text.charCodeAt(0);

            document.getElementById("demo").innerHTML = code;
        </script>
    

Practical examples

example: using the charCodeAt() method on a string.

code:
                    <div>
                        <p id="at-1"></p>
                        <p id="at-2"></p>
                        <p id="at-3"></p>
                        <p id="at-4"></p>
                        <p id="at-5"></p>
                        <p id="at-6"></p>
                        <p id="at-7"></p>
                    </div>
                    <script>
                        let text = "HELLO WORLD";
                        document.getElementById("at-1").innerHTML = "string : " + text;
                        let code = text.charCodeAt(1);
                        document.getElementById("at-2").innerHTML = "code : " + code;
                        let code2 = text.charCodeAt(text.length-1);
                        document.getElementById("at-3").innerHTML = "code : " + code2;
                        let code3 = text.charCodeAt(15);
                        document.getElementById("at-4").innerHTML = "code : " + code3;
                        let code4 = text.charCodeAt();
                        document.getElementById("at-5").innerHTML = "code : " + code4;
                        
                    </script>