javascript
  1. javascript-charcodeat

JavaScript charCodeAt()

The charCodeAt() method is a JavaScript string method that returns the Unicode value of the character at a specified index within a string.

Syntax

The syntax for the charCodeAt() method is:

str.charCodeAt(index)
  • str: the string to extract a Unicode value from.
  • index: the position of the character within the string to return the Unicode value for.

Example

Here's an example of how to use the charCodeAt() method:

const str = "Hello, World!";
const index = 0;
const unicodeValue = str.charCodeAt(index);

console.log(`The Unicode value of the character at index ${index} is ${unicodeValue}.`);

Output

The output of the code above would be:

The Unicode value of the character at index 0 is 72.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>charCodeAt() Method Example</title>
</head>
<body>

<!-- Display area for the output -->
<div id="output"></div>

<script>
    // Your JavaScript code
    const str = "Hello, World!";
    const index = 0;
    const unicodeValue = str.charCodeAt(index);

    // Display the output in the HTML document
    document.getElementById('output').innerHTML = `
        <p>The Unicode value of the character at index ${index} is ${unicodeValue}.</p>
    `;
</script>

</body>
</html>
Try Playground

Explanation

The charCodeAt() method returns the Unicode value of the character at the specified index within the string. In the example above, we set the str variable to "Hello, World!" and the index variable to 0, which means we want to get the Unicode value of the first character in the string. The Unicode value of the character "H" is 72, so that's what gets returned and output to the console.

Use

The charCodeAt() method is useful when you need to work with Unicode characters in JavaScript, especially when you need to convert them to or from other character encodings.

Important Points

Here are a few important things to know about the charCodeAt() method:

  • If the index passed to the method is out of range (less than 0 or greater than the length of the string minus 1), NaN will be returned.
  • The returned Unicode value is an integer ranging from 0 to 65535.
  • For characters that consist of more than one Unicode value (such as emoji or some Chinese characters), charCodeAt() will only return the value for the first character in the sequence.

Summary

The charCodeAt() method in JavaScript is a useful tool for working with Unicode characters in a string. By providing an index to the method, you can retrieve a Unicode value that represents the character at that position. Whether you're working with encodings or need to parse text data, charCodeAt() is a key method for JavaScript developers to have in their toolkit.

Published on: