Javascript:获取字符串的最后几个字符

时间:2017-04-11 09:34:20

标签: javascript string

如果我们将字符串存储在变量中,这是一个微不足道的问题。但出于好奇,我需要了解如何在不将字符串存储在变量中的情况下实现这一目标吗?

//  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

2 个答案:

答案 0 :(得分:3)

  

如何获得最后7个字符

尝试

"amangupta".slice(-7)

答案 1 :(得分:0)

如果没有额外的变量,您需要再次使用该字符串

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