Languages
[Edit]
EN

TypeScript - get last n characters of string

0 points
Created by:
Paluskitten
356

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: 

  1. Using substring() method,
  2. Using slice() method.

1. String substring() method example

Edit

The below example shows how to use .substring() method to get the last n characters of the text string. 

Runnable example:

Output:

Another practical example:

Output:

2. String slice() method example

Edit

The below example shows the use of .slice() method with negative index to get the last n characters of the text string.

Runnable example:

Output:

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:

Output:

1
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