The charAt() method of the String class in JavaScript returns the character (exactly one UTF-16 code unit) at the specified index.
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.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the character to retrieve. |
String.charAt() returns value of type String
.
In JavaScript, we can use charAt()
method to get a character at a specific index in the string.
For example,
str
with the value 'Hello'
.charAt()
method with the index 2
to retrieve the character at that index.2
, which is 'l'
, is stored in the variable charAtIndex2
.charAtIndex2
to the console using console.log()
method.const str = 'Hello';
const charAtIndex2 = str.charAt(2);
console.log(charAtIndex2);
l
In JavaScript, we can use charAt()
method with the index str.length - 1
to get the last character in the string.
For example,
str
with the value 'Hello'
.charAt()
method with the index str.length - 1
to retrieve the last character.'o'
, is stored in the variable lastChar
.lastChar
to the console using console.log()
method.const str = 'Hello';
const lastChar = str.charAt(str.length - 1);
console.log(lastChar);
o
In JavaScript, we can use charAt()
method with the index 0
to get the first character in the string.
For example,
str
with the value 'Hello'
.charAt()
method with the index 0
to retrieve the first character.'H'
, is stored in the variable firstChar
.firstChar
to the console using console.log()
method.const str = 'Hello';
const firstChar = str.charAt(0);
console.log(firstChar);
H
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.