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
Parameter | Optional/Required | Description |
---|---|---|
index | required | The 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,
- We define a string variable
str
with the value'Hello'
. - We use the
at()
method with the index2
to retrieve the character at that index. - The character at index
2
, which is'l'
, is stored in the variablecharAtIndex2
. - We log
charAtIndex2
to the console usingconsole.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,
- We define a string variable
str
with the value'Hello'
. - We use the
at
method with the index-1
to retrieve the last character. - The last character, which is
'o'
, is stored in the variablelastChar
. - We log
lastChar
to the console usingconsole.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,
- We define a string variable
str
with the value'Hello'
. - We use the
at()
method with the index0
to retrieve the first character. - The first character, which is
'H'
, is stored in the variablefirstChar
. - We log
firstChar
to the console usingconsole.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.