EN
TypeScript - get nth string character
0 points
In this article, we would like to show you how to get n-th string character in TypeScript.
Quick solution:
xxxxxxxxxx
1
const text: string = 'Dirask';
2
3
console.log(text.charAt(0)); // D
4
// ^
5
// |
6
// character on 1st position (index=0)
or:
xxxxxxxxxx
1
const text: string = 'Dirask';
2
3
console.log(text[0]); // D
In this example, we use built-in String
charAt()
method to get n-th string character.
xxxxxxxxxx
1
const text: string = 'Dirask';
2
3
const index: number = 3;
4
const character: string = text.charAt(index);
5
6
console.log(character); // a
String characters can be accessed with []
like in array case.
xxxxxxxxxx
1
const text: string = 'Dirask';
2
3
const index: number = 3;
4
const character: string = text[index];
5
6
console.log(character); // a