JavaScript(JS) string method - charcodeat

ww‮w‬.theitroad.com

The charCodeAt() method is a built-in method of the JavaScript String object. It returns the Unicode value of the character at the specified index in a string.

Here's the syntax:

str.charCodeAt(index)

where str is the string to get the character code from, and index is the zero-based index of the character to retrieve.

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

const myString = "hello world";
console.log(myString.charCodeAt(1)); // 101

In this example, we create a string myString with the value "hello world". We use the charCodeAt() method to retrieve the Unicode value of the character at index 1, which is "e". The resulting value is 101.

If the specified index is out of range, charCodeAt() returns NaN.

console.log(myString.charCodeAt(100)); // NaN

In this example, we try to retrieve the character at index 100, which is out of range for the length of the string. charCodeAt() returns NaN.

The charCodeAt() method is a useful tool for working with Unicode values of characters in a string. It can be used in combination with other methods such as String.fromCharCode() to manipulate and convert Unicode values to characters and vice versa.