JavaScript - codePointAt() method

revision:


Category : string

The codePointAt() method returns the Unicode of the character at an index (position) in a string.The index of the first character is 0, the second is 1, ....

Difference between charCodeAt() and codePointAt() : charCodeAt() is UTF-16, codePointAt() is Unicode. charCodeAt() returns a number between 0 and 65535. Both methods return an integer representing the UTF-16 code of a character, but only codePointAt() can return the full value of a Unicode value greather 0xFFFF (65535).

Syntax :

        string.codePointAt(index)    
    

Parameters:

index : optional. A number. The index (position) of the character in a string. Default is 0.

Examples:

        <p>Get the code point at the first character:</p>
        <p id="demo"></p>
       <script>
            let text = "HELLO WORLD";
            let code = text.codePointAt(0);
            document.getElementById("demo").innerHTML = code;
        </script>
    

Practical examples

example: using the codePointAt() method on strings

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.codePointAt(1);
                        document.getElementById("at-2").innerHTML = "code : " + code;
                        let code2 = text.codePointAt(text.length-1);
                        document.getElementById("at-3").innerHTML = "code : " + code2;
                        let code3 = text.codePointAt(15);
                        document.getElementById("at-4").innerHTML = "code : " + code3;
                        let code4 = text.codePointAt();
                        document.getElementById("at-5").innerHTML = "code : " + code4;
                        
                    </script>