EN
TypeScript - get last n characters of string
0 points
In this article, we would like to show you how to get the last n characters 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 n
characters of the text
string.
Runnable example:
xxxxxxxxxx
1
const text: string = '12345';
2
3
const n: number = 3;
4
const substring: string = text.substring(text.length - n);
5
6
console.log(substring); // 345
Output:
xxxxxxxxxx
1
345
Another practical example:
xxxxxxxxxx
1
const n = 3;
2
3
console.log(''.substring(''.length - n) === ''); // true means string is empty
4
console.log('1'.substring('1'.length - n)); // 1
5
console.log('12'.substring('12'.length - n)); // 12
6
console.log('123'.substring('123'.length - n)); // 123
7
console.log('1234'.substring('1234'.length - n)); // 234
8
console.log('12345'.substring('12345'.length - n)); // 345
Output:
xxxxxxxxxx
1
true
2
1
3
12
4
123
5
234
6
345
The below example shows the use of .slice()
method with negative index to get the last n characters of the text
string.
Runnable example:
xxxxxxxxxx
1
const text: string = '12345';
2
3
const n: number = 3;
4
const substring: string = text.slice(-n);
5
6
console.log(substring); // 345
Output:
xxxxxxxxxx
1
345
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
const n: number = 3;
2
3
console.log(''.slice(-n) === ''); // true means string is empty
4
console.log('1'.slice(-n)); // 1
5
console.log('12'.slice(-n)); // 12
6
console.log('123'.slice(-n)); // 123
7
console.log('1234'.slice(-n)); // 234
8
console.log('12345'.slice(-n)); // 345
Output:
xxxxxxxxxx
1
true
2
1
3
12
4
123
5
234
6
345