JavaScript String charAt()

Definition and usage

charAt() The method returns the character at the specified index (subscript) in the string.

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 this page).

See also:

charCodeAt() method

Instance

Example 1

Get the first character of the string:

let text = "HELLO WORLD";
let letter = text.charAt(0);

Try it yourself

Example 2

Get the second character of the string:

let text = "HELLO WORLD";
let letter = text.charAt(1);

Try it yourself

Example 3

Get the last character of the string:

let text = "HELLO WORLD";
let letter = text.charAt(text.length-1);

Try it yourself

Example 4

Indexes out of range return an empty string:

let text = "HELLO WORLD";
let letter = text.charAt(15);

Try it yourself

Example 5

The default index is 0:

let text = "HELLO WORLD";
let letter = text.charAt();

Try it yourself

Example 6

Invalid index is converted to 0:

let text = "HELLO WORLD";
let letter = text.charAt(3.14);

Try it yourself

Syntax

string.charAt(n)

Parameter

Parameter Description
n Required. Number. The index (subscript) of the character.

Return value

Type Description
String

Specifies the character at the index.

If the index is invalid, it returns an empty string ("

Description

If the parameter n Not between 0 and stringIf the index is between .length-1, the method returns an empty string.

Note:JavaScript does not have a character data type different from the string type, so the returned character is a string of length 1.

Browser support

charAt() 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
Stöd Stöd Stöd Stöd Stöd Stöd

Relaterade sidor

JavaScript-sträng

JavaScript-strängmetoder

JavaScript-strängsökning