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
Parameter | Optional/Required | Description |
---|---|---|
index | required | The 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,
- We define a string variable
str
with the value'Hello'
. - We use the
charAt()
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.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,
- We define a string variable
str
with the value'Hello'
. - We use the
charAt()
method with the indexstr.length - 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.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,
- We define a string variable
str
with the value'Hello'
. - We use the
charAt()
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.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.