EN
TypeScript - remove suffix from string
0 points
In this article, we would like to show you how to remove suffix from string in TypeScript.
Quick solution:
xxxxxxxxxx
1
const text: string = 'ABCD';
2
3
// replace the last two characters with empty string
4
const result1: string = text.replace(/.{0,2}$/, '');
5
6
// remove the last two characters
7
const result2: string = text.slice(0, -2);
8
9
// remove the last two characters
10
const result3: string = text.substring(0, text.length - 2);
11
12
console.log(result1); // AB
13
console.log(result2); // AB
14
console.log(result3); // AB
In this example, we use replace()
method with regex to replace the last two letters (CD
) with an empty string.
xxxxxxxxxx
1
const text: string = 'ABCD';
2
3
// replace the last two characters with empty string
4
const result: string = text.replace(/.{0,2}$/, '');
5
6
console.log(result); // AB
Output:
xxxxxxxxxx
1
AB
In this example, we use slice()
method to remove the last two letters from the text
.
xxxxxxxxxx
1
const text: string = 'ABCD';
2
3
// remove the last two characters
4
const result: string = text.slice(0, -2);
5
6
console.log(result); // AB
Output:
xxxxxxxxxx
1
AB
In this example, we use substring()
method to remove the last two letters from the text
.
xxxxxxxxxx
1
const text: string = 'ABCD';
2
3
// remove the last two characters
4
const result: string = text.substring(0, text.length - 2);
5
6
console.log(result); // AB
Output:
xxxxxxxxxx
1
AB