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
1

2 Answers 2

11

How to get last 7 characters

Try

"amangupta".slice(-7)
Sign up to request clarification or add additional context in comments.

Comments

0

Without an extra variable you need to use the string again

"amangupta".substring("amangupta".length - 7, "amangupta".length);

1 Comment

"amangupta" is a random string getting generated from some function, which I should have included in my question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.