JavaScript String at()
Syntax & Examples


String.at() method

The at() method of the String class in JavaScript returns the character (exactly one UTF-16 code unit) at the specified index. It accepts negative integers, which count back from the last string character.


Syntax of String.at()

The syntax of String.at() method is:

at(index)

This at() method of String returns the character (exactly one UTF-16 code unit) at the specified index. Accepts negative integers, which count back from the last string character.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the character to retrieve. Negative integers count back from the last string character.

Return Type

String.at() returns value of type String.



✐ Examples

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

In JavaScript, we can use at() method to get 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 at() 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.at(2);
console.log(charAtIndex2);

Output

l

2 Using at() method to get the last character

In JavaScript, we can use at() method to get the last character in the string using index = -1.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the at method with the index -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.at(-1);
console.log(lastChar);

Output

o

3 Using at() method to get the first character

In JavaScript, we can use at() method to get the first character in the string using index = 0.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We use the at() 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.at(0);
console.log(firstChar);

Output

H

Summary

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