Languages
[Edit]
EN

JavaScript - get last 3 characters of string

0 points
Created by:
Rogan-Wilkes
727

In this article, we would like to show you how to get the last 3 characters of a string in JavaScript.

Below we present two solutions on how to do that: 

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

1. String substring() method example

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

Runnable example:

// ONLINE-RUNNER:browser;

var text = '12345';
var substring = text.substring(text.length - 3);

console.log(substring); // 345

Another practical example:

// ONLINE-RUNNER:browser;

// true means string is empty

console.log( "".substring("".length - 3) === "" ); // empty
console.log( "1".substring("1".length - 3) ); // 1
console.log( "12".substring("12".length - 3) ); // 12
console.log( "123".substring("123".length - 3) ); // 123
console.log( "1234".substring("1234".length - 3) ); // 234
console.log( "12345".substring("12345".length - 3) ); // 345

2. String slice() method example

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

Runnable example:

// ONLINE-RUNNER:browser;

var text = '12345';
var substring = text.slice(-3);

console.log(substring); // 345

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:

// ONLINE-RUNNER:browser;

// true means string is empty

console.log( "".slice(-3) === "" ); // empty
console.log( "1".slice(-3) ); // 1
console.log( "12".slice(-3) ); // 12
console.log( "123".slice(-3) ); // 123
console.log( "1234".slice(-3) ); // 234
console.log( "12345".slice(-3) ); // 345

 References

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.

Cross technology - get last 3 characters of string

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