我有

var id="ctl03_Tabs1";

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


当前回答

获取最后一个字符很容易,因为你可以把字符串当作数组:

var lastChar = id[id.length - 1];

要获取字符串的一部分,可以使用substr函数或substring函数:

id.substr(id.length - 1); //get the last character
id.substr(2);             //get the characters from the 3rd character on
id.substr(2, 1);          //get the 3rd character
id.substr(2, 2);          //get the 3rd and 4th characters

substr和substring之间的区别在于如何处理第二个(可选)参数。在substr中,它是来自索引(第一个参数)的字符量。在substring中,它是字符切片应该结束的位置的索引。

其他回答

一种方法是使用slice,如下所示:

var id="ctl03_Tabs1";
var temp=id.slice(-5);

因此temp的值将是“Tabs1”。

const id = 'ctl03_Tabs1';
id.at(-1); // Returns '1'

At支持负整数从最后一个字符串字符开始计数。


文档:字符串/和

假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展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.substring(id.length - 1, id.length);

没有必要使用substr方法来获取字符串的单个字符!

以Jamon Holmgren为例,我们可以改变substr方法,简单地指定数组的位置:

var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"