JavaScript String charAt()
Syntax & Examples


String.charAt() method

The charAt() method of the String class in JavaScript returns the character (exactly one UTF-16 code unit) at the specified index.


Syntax of String.charAt()

The syntax of String.charAt() method is:

charAt(index)

This charAt() method of String returns the character (exactly one UTF-16 code unit) at the specified index.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the character to retrieve.

Return Type

String.charAt() returns value of type String.



✐ Examples

1 Using charAt() method to get a character at a specific index

In JavaScript, we can use charAt() method to get a character at a specific index in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charAt() method with the index 2 to retrieve the character at that index.
  3. The character at index 2, which is 'l', is stored in the variable charAtIndex2.
  4. We log charAtIndex2 to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const charAtIndex2 = str.charAt(2);
console.log(charAtIndex2);

Output

l

2 Using charAt() method to get the last character

In JavaScript, we can use charAt() method with the index str.length - 1 to get the last character in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charAt() method with the index str.length - 1 to retrieve the last character.
  3. The last character, which is 'o', is stored in the variable lastChar.
  4. We log lastChar to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const lastChar = str.charAt(str.length - 1);
console.log(lastChar);

Output

o

3 Using charAt() method to get the first character

In JavaScript, we can use charAt() method with the index 0 to get the first character in the string.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the charAt() method with the index 0 to retrieve the first character.
  3. The first character, which is 'H', is stored in the variable firstChar.
  4. We log firstChar to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const firstChar = str.charAt(0);
console.log(firstChar);

Output

H

Summary

In this JavaScript tutorial, we learned about charAt() method of String: the syntax and few working examples with output and detailed explanation for each example.