JavaScript | String.prototype.charCodeAt()

str.charCodeAt() function returns a Unicode character set code unit of the character present at the index in the string specified as the argument. The syntax of the function is as follows:

str.charCodeAt(index)

Arguments
The only argument to this function is the index of the character in the string whose Unicode is to be used. The range of the index is from 0 to length – 1.

Return value
This function returns the Unicode (ranging between 0 and 65535) of the character whose index is provided to the function as the argument. If the index provided is out of range the this function returns NaN.

Examples for the above function are provided below:

Example 1:

Input:
var str = 'ephemeral';
print(str.charCodeAt(4));

Output:
109

In this example the function charCodeAt() extracts the character from the string at index 4. Since this character is m, therefore this function returns the Unicode sequence as 109.

Example 2:

Input:
var str = 'ephemeral';
print(str.charCodeAt(20));

Output:
NaN

In this example the function charCodeAt() extracts the character from the string at index 20. Since the index is out of bounds for the string, therefore this function returns the answer as NaN.

Codes for the above function are provided below:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript to illustrate charCodeAt() function
  
function func() {
    var str = 'ephemeral';
  
    // Finding the code of the character at
    // given index 
    var value = str.charCodeAt(4);
    document.write(value);    
}
  
func();
</script>

chevron_right


Output:

109

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript to illustrate charCodeAt() function
  
function func() {
    var str = 'ephemeral';
  
    // Finding the code of the character 
    // at given index 
    var value = str.charCodeAt(20);
  
    document.write(value);    
}
func();
</script> 

chevron_right


Output:

NaN


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.