JavaScript String charCodeAt() 方法

定义和用法

charCodeAt() 方法返回字符串中规定索引(下标)处字符的 Unicode。

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

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

See also:

charAt() method

charCodeAt() vs codePointAt()

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

charCodeAt() returns numbers between 0 and 65535.

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

Tip:For more information about 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 Unicode of the character at the given index.
NaN if the index is invalid.

Technical details

return value

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

description

charCodeAt() method and 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() method returns NaN.

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

browser support

charCodeAt() is ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Gudanarwa Gudanarwa Gudanarwa Gudanarwa Gudanarwa Gudanarwa

Samun da yake da alama

JavaScript ɗanar

JavaScript ɗanar

JavaScript ɗanar