Languages
[Edit]
EN

JavaScript - get last n characters of string

0 points
Created by:
Hayley-Mooney
377

In this article, we would like to show you how to get the last n 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

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

Runnable example:

// ONLINE-RUNNER:browser;

var text = '12345';

var n = 3;
var substring = text.substring(text.length - n);

console.log(substring); // 345

Another practical example:

// ONLINE-RUNNER:browser;

var n = 3;

console.log( "".substring("".length - n) === "" ); // true means string is empty
console.log( "1".substring("1".length - n) ); // 1
console.log( "12".substring("12".length - n) ); // 12
console.log( "123".substring("123".length - n) ); // 123
console.log( "1234".substring("1234".length - n) ); // 234
console.log( "12345".substring("12345".length - n) ); // 345

2. String slice() method example

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

Runnable example:

// ONLINE-RUNNER:browser;

var text = '12345';

var n = 3;
var substring = text.slice(-n);

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;

var n = 3;

console.log( "".slice(-n) === "" ); // true means string is empty
console.log( "1".slice(-n) ); // 1
console.log( "12".slice(-n) ); // 12
console.log( "123".slice(-n) ); // 123
console.log( "1234".slice(-n) ); // 234
console.log( "12345".slice(-n) ); // 345

 References

JavaScript - String (popular problems)

JavaScript - get last n 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