EN
TypeScript - get last 2 characters of string
0
points
In this article, we would like to show you how to get the last 2 characters of a string in TypeScript.
Below we present two solutions on how to do that:
- Using
substring()method, - Using
slice()method.
1. String substring() method example
The below example shows how to use .substring() method to get the last 2 characters of the text string.
Runnable example:
const text: string = '12345';
const substring: string = text.substring(text.length - 2);
console.log(substring); // 45
Output:
45
Another practical example:
// true means string is empty
console.log(''.substring(''.length - 2) === ''); // empty
console.log('1'.substring('1'.length - 2)); // 1
console.log('12'.substring('12'.length - 2)); // 12
console.log('123'.substring('123'.length - 2)); // 23
console.log('1234'.substring('1234'.length - 2)); // 34
console.log('12345'.substring('12345'.length - 2)); // 45
Output:
true
1
12
23
34
45
2. String slice() method example
The below example shows the use of .slice() method with a negative index to get the last 2 characters of the text string.
Runnable example:
const text: string = '12345';
const substring: string = text.slice(-2);
console.log(substring); // 45
Output:
45
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:
// true means string is empty
console.log(''.slice(-2) === ''); // empty
console.log('1'.slice(-2)); // 1
console.log('12'.slice(-2)); // 12
console.log('123'.slice(-2)); // 23
console.log('1234'.slice(-2)); // 34
console.log('12345'.slice(-2)); // 45
Output:
true
1
12
23
34
45