Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to return a number indicating the Unicode value of the character?
The charCodeAt() method returns a number indicating the Unicode value of the character at the given index. Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match of the ASCII character encoding.
Syntax
string.charCodeAt(index)
Parameters
- index ? An integer between 0 and 1 less than the length of the string; if unspecified, defaults to 0.
Return Value
Returns a number representing the Unicode code point of the character at the specified index. If the index is out of range, returns NaN.
Example
Here's how to get Unicode values of characters at different positions:
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
var str = "Hello World";
document.write("str.charCodeAt(0) is: " + str.charCodeAt(0));
document.write("<br>str.charCodeAt(1) is: " + str.charCodeAt(1));
document.write("<br>str.charCodeAt(6) is: " + str.charCodeAt(6));
document.write("<br>str.charCodeAt(10) is: " + str.charCodeAt(10));
// Out of range example
document.write("<br>str.charCodeAt(20) is: " + str.charCodeAt(20));
</script>
</body>
</html>
Output
str.charCodeAt(0) is: 72 str.charCodeAt(1) is: 101 str.charCodeAt(6) is: 87 str.charCodeAt(10) is: 100 str.charCodeAt(20) is: NaN
Common Use Cases
The charCodeAt() method is useful for:
- Converting characters to their ASCII/Unicode values
- Implementing custom string comparison algorithms
- Creating character encoding/decoding functions
- Validating character ranges in input strings
Key Points
- Returns Unicode code points as numbers
- Index starts from 0
- Returns
NaNfor invalid indices - ASCII characters (A-Z, a-z, 0-9) have code points 32-126
Conclusion
The charCodeAt() method provides access to Unicode values of string characters. Use it when you need to work with character codes for encoding, validation, or custom string operations.
Advertisements
