Languages
[Edit]
EN

TypeScript - remove last 2 characters from string

0 points
Created by:
Diana
720

In this article, we're going to have a look at how to remove the last 2 characters from the string in TypeScript.

1. String slice() method example

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. 

const text: string = 'abcde';
const substring: string = text.slice(0, -2);

console.log(substring); // abc

Output:

abc

2. String substring() method example

This is an alternative approach to slice method based solution.

const text: string = 'abcde';
const substring: string = text.substring(0, text.length - 2);

console.log(substring); // abc

Output:

abc

3. String replace() method example

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.

const text: string = 'abcde';
const substring: string = text.replace(/.{0,2}$/, '');

console.log(substring); // abc

Output:

abc
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join