我有

var id="ctl03_Tabs1";

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


当前回答

要获取字符串的最后一个字符,可以使用split(").pop()函数。

const myText = "The last character is J";
const lastCharater = myText.split('').pop();
console.log(lastCharater); // J

它的工作原理是因为当split(")函数有empty(")作为参数时,字符串的每个字符都被更改为数组的一个元素。因此,我们可以使用pop()函数返回该数组的最后一个元素,即'J'字符。

其他回答

这里有两个例子,告诉你总是最后一个字符

var id=“ctl03_Tabs1”; console.log(id.charAt(id.length - 1)); console.log(id[id.length - 1]);

检查子字符串函数。

要得到最后一个字符:

id.substring(id.length - 1, id.length);

性能

今天2020.12.31我在Chrome v87、Safari v13.1.2和Firefox v84上的MacOs HighSierra 10.13.6上执行测试,以获得最后一个字符大小写(最后N个字母大小写结果,为了清晰起见,我在单独的答案中给出)。

结果

适用于所有浏览器

解D E F是非常快或最快的 解G H是最慢的

细节

我执行2个测试用例:

当字符串有10个字符-你可以在这里运行它 当字符串有1M字符-你可以在这里运行它

下面的代码片段给出了解决方案 一个 B C D E F G (my) H (my)

//https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string // https://stackoverflow.com/a/30916653/860099 function A(s) { return s.substr(-1) } // https://stackoverflow.com/a/5873890/860099 function B(s) { return s.substr(s.length - 1) } // https://stackoverflow.com/a/17489443/860099 function C(s) { return s.substring(s.length - 1, s.length); } // https://stackoverflow.com/a/50395190/860099 function D(s) { return s.slice(-1); } // https://stackoverflow.com/a/50374396/860099 function E(s) { return s.charAt(s.length-1); } // https://stackoverflow.com/a/17489443/860099 function F(s) { return s[s.length-1]; } // my function G(s) { return s.match(/.$/); } // my function H(s) { return [...s].pop(); } // -------------------- // TEST // -------------------- [A,B,C,D,E,F,G,H].map(f=> { console.log( f.name + ' ' + f('ctl03_Tabs1') )}) This shippet only presents functions used in performance tests - it not perform tests itself!

这里是chrome的示例结果

你可以用切片

id.slice(-5);

编辑:正如其他人指出的那样,使用slice(-5)而不是substr。但是,请参阅答案底部的.split().pop()解决方案以了解另一种方法。

最初的回答:

你需要使用Javascript字符串方法.substr()结合.length属性。

var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"

这将获取从id开始的字符。长度- 5,由于.substr()的第二个参数被省略,因此将一直持续到字符串的末尾。

您也可以使用.slice()方法,正如其他人在下面指出的那样。

如果你只是想找到下划线后面的字符,你可以使用这个:

var tabId = id.split("_").pop(); // => "Tabs1"

这将字符串拆分为一个下划线数组,然后从数组中“弹出”最后一个元素(这是您想要的字符串)。