EN
TypeScript - remove last 2 characters from string
0 points
In this article, we're going to have a look at how to remove the last 2 characters from the string in TypeScript.
This approach allows getting substring by using negative indexes. So by using 0
and -2
indexes as the range we get <0, text.length - 2>
text range.
xxxxxxxxxx
1
const text: string = 'abcde';
2
const substring: string = text.slice(0, -2);
3
4
console.log(substring); // abc
Output:
xxxxxxxxxx
1
abc
This is an alternative approach to slice
method based solution.
xxxxxxxxxx
1
const text: string = 'abcde';
2
const substring: string = text.substring(0, text.length - 2);
3
4
console.log(substring); // abc
Output:
xxxxxxxxxx
1
abc
There is another trick that allows replacing all characters that match expression conditions. By using .{0,2}$
pattern we match any 2 characters (up to 2 characters) that are located at the end of the string.
xxxxxxxxxx
1
const text: string = 'abcde';
2
const substring: string = text.replace(/.{0,2}$/, '');
3
4
console.log(substring); // abc
Output:
xxxxxxxxxx
1
abc