我有

var id="ctl03_Tabs1";

使用JavaScript,如何获得最后五个字符或最后一个字符?


当前回答

Substr函数允许您使用减号来获取最后一个字符。

var string = "hello";
var last = string.substr(-1);

它非常灵活。 例如:

// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"

其他回答

假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展string类来完成这一点:

String.prototype.endsWith = function (substring) {
  if(substring.length > this.length) return false;
  return this.substr(this.length - substring.length) === substring;
};

允许您执行以下操作:

var aSentenceToPonder = "This sentence ends with toad"; 
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true

你可以用切片

id.slice(-5);

不要使用已弃用的.substr()!

使用.slice()方法,因为它是跨浏览器兼容的(见IE问题)。 或者使用.substring()方法。

它们在需求上有一些细微的差异,这些差异被正确地记录在:

const id = "ctl03_Tabs1"; console.log (id.slice (5));/ /输出:Tabs1 console.log (id.slice (1));/ /输出:1 //下面是比较慢的 console.log (id.substring (id。长度- 5));/ /输出:Tabs1 console.log (id.substring (id。长度- 1));/ /输出:1

const r = '6176958e92d42422203a3c58'; 
r.slice(-4)

结果' 3 c58 '

r.slice(-1)

结果“8”

var id="ctl03_Tabs1";
var res = id.charAt(id.length-1);

我发现了这个问题,通过一些研究,我发现这是得到最后一个字符的最简单的方法。

正如其他人所提到的,为了完整起见,添加了最后5个:

var last5 = id.substr(-5);