0

This is a trivial problem if we are storing string in a variable. But out of curiosity, I need to understand how to achieve this without storing string in variable?

//  To get first few characters of a string, we can do something like this:
var x = "amangupta".substring(0,7); //amangup

//  How to get last 7 characters
var x = "amangupta".substring(this.length - 7, this.length); // does not work, looking for similar approach

var str = "amangupta";
var x = str.substring(str.length - 7, str.length); // will work fine
Aman Gupta
  • 3,627
  • 4
  • 40
  • 64
  • This is a duplicate question please go to this answer http://stackoverflow.com/a/15473635/5452965 – codtex Apr 11 '17 at 09:38

2 Answers2

9

How to get last 7 characters

Try

"amangupta".slice(-7)
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Without an extra variable you need to use the string again

"amangupta".substring("amangupta".length - 7, "amangupta".length);
Der Flo
  • 62
  • 5
  • "amangupta" is a random string getting generated from some function, which I should have included in my question. – Aman Gupta Apr 11 '17 at 09:37