JavaScript charCodeAt() String Method

Last Updated on by in JavaScript
To get the Unicode number (UTF-16 ) of any character from any given position we use JavaScript charCodeAt() method. In the below example we are getting the UTF-16 value of the second character.

let str = "Avenger EndGame";

// output: 118

To make you understand about this powerful function we are going to use a for loop in which we’ll get the UTF-16 or Unicode value of every character of a given string.

Check out the output below:








JavaScript charCodeAt() Method Syntax

Parameter Detail
position This is optional, we pass the position of the character from the string whose Unicaode value we are willing to get. It takes 0 position by default, If we don’t pass the parameter in it.

When No Argument is Passed

Let us find out what happens when we don’t provide any argument to JavaScript charCodeAt() method.

let string = 'Avengers';

// output: 65

As you can see we haven’t provided any value and still it returned 65. Well as I said before when we don’t provide any parameter, it takes the 0 positions as the first parameter. So whatever character is there at 0 position it will returns that characters UTF-16 code.

Converting Unicode Value (UTF-16) to Character

We can convert Char code to Char using String.fromCharCode() method.

// output: Z

// output: d

// output: Ĥ

charCodeAt() Browser Support

Chrome Firefox Edge Safari Opera
Yes Yes Yes Yes Yes

Check out the full browser compatibility report on MDN Web Docs

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.