JavaScript String charCodeAt() metod
- Föregående sida
- Nästa sida
- Gå tillbaka till föregående nivå JavaScript String referens manual
Definition och användning
charCodeAt()
Metoden returnerar teckenet vid den angivna indexen (index) i strängen som 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 following example).
See also:
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);
Example 2
Get the Unicode of the second character:
let text = "HELLO WORLD"; let code = text.charCodeAt(1);
Example 3
Get the Unicode of the last character in the string:
let text = "HELLO WORLD"; let code = text.charCodeAt(text.length-1);
Example 4
Get the Unicode of the 16th character:
let text = "HELLO WORLD"; let code = text.charCodeAt(15);
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 the 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 operation performed by the method is 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 web browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Stöd | Stöd | Stöd | Stöd | Stöd | Stöd |
- Föregående sida
- Nästa sida
- Gå tillbaka till föregående nivå JavaScript String referens manual