JavaScript String charCodeAt() Method

Definition and Usage

charCodeAt() The method returns the Unicode character at the specified index (index) in the string.

The index of the first character is 0, the second is 1, ... and so on.

The index of the last character is string length - 1 (see the following example).

See also:

charAt() method

charCodeAt() vs codePointAt()

charCodeAt() is UTF-16,codePointAt() is Unicode.

charCodeAt() returns numbers between 0 and 65535.

Both methods return integers representing the UTF-16 code of the character, but only codePointAt() Can return the full value of the Unicode value greater than 0xFFFF (65535).

Tip:For more information on the Unicode character set, please visit our Unicode reference manual.

Example

Example 1

Get the Unicode of the first character in the string:

let text = "HELLO WORLD";
let code = text.charCodeAt(0);

Try it yourself

Example 2

Get the Unicode of the second character:

let text = "HELLO WORLD";
let code = text.charCodeAt(1);

Try it yourself

Example 3

Get the Unicode of the last character in the string:

let text = "HELLO WORLD";
let code = text.charCodeAt(text.length-1);

Try it yourself

Example 4

Get the Unicode of the 16th character:

let text = "HELLO WORLD";
let code = text.charCodeAt(15);

Try it yourself

Syntax

string.charCodeAt(n)

Parameter

Parameter Description
n

Optional. Number. The index (subscript) of the character.

Default value = 0.

Return value

Type Description
Number The Unicode of the character at the given index.
NaN If the index is invalid.

Technical details

Return value

string of n The Unicode encoding of a character. This return value is a 16-bit integer between 0 and 65535.

Description

charCodeAt() method is similar to charAt() The operations performed by the method are similar, but the former returns the encoding of the character at the specified position, while the latter returns a substring containing the character itself. If n is negative, or greater than or equal to the length of the string, then charCodeAt() The method returns NaN.

For information on how to create a string from Unicode encoding, please refer to fromCharCode() method.

Browser support

charCodeAt() It is an ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support

Related Pages

JavaScript String

JavaScript String Methods

JavaScript String Search