JavaScript charCodeAt() String Method
Last updated on: by Digamber
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";
str.charCodeAt(1)
// 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:
65
118
101
110
103
101
114
JavaScript charCodeAt() Method Syntax
str.charCodeAt([position]);
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';
console.log(string.charCodeAt());
// 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.
String.fromCharCode(90)
// output: Z
String.fromCharCode(100)
// output: d
String.fromCharCode(0x124)
// 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