EN
TypeScript - get last character of string
0 points
In this article, we would like to show you how to get the last character of a string in TypeScript.
Below we present two solutions on how to do that:
- Using
substring()
method, - Using
slice()
method.
The below example shows how to use .substring()
method to get the last character of the text
string.
Runnable example:
xxxxxxxxxx
1
const text: string = '12345';
2
const substring: string = text.substring(text.length - 1);
3
4
console.log(substring); // 5
Output:
xxxxxxxxxx
1
5
Another practical example:
xxxxxxxxxx
1
// true means string is empty
2
3
console.log(''.substring(''.length - 1) === ''); // empty
4
console.log('1'.substring('1'.length - 1)); // 1
5
console.log('12'.substring('12'.length - 1)); // 2
6
console.log('123'.substring('123'.length - 1)); // 3
7
console.log('1234'.substring('1234'.length - 1)); // 4
8
console.log('12345'.substring('12345'.length - 1)); // 5
Output:
xxxxxxxxxx
1
true
2
1
3
2
4
3
5
4
6
5
The below example shows the use of .slice()
method with a negative index to get the last character of the text
string.
Runnable example:
xxxxxxxxxx
1
const text: string = '12345';
2
const substring: string = text.slice(-1);
3
4
console.log(substring); // 5
Output:
xxxxxxxxxx
1
5
In the second example, we can see that we can also use string slice()
with negative indexes on a shorter or empty string which will give us the following results:
xxxxxxxxxx
1
// true means string is empty
2
3
console.log(''.slice(-1) === ''); // empty
4
console.log('1'.slice(-1)); // 1
5
console.log('12'.slice(-1)); // 2
6
console.log('123'.slice(-1)); // 3
7
console.log('1234'.slice(-1)); // 4
8
console.log('12345'.slice(-1)); // 5
Output:
xxxxxxxxxx
1
true
2
1
3
2
4
3
5
4
6
5