我有

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"

其他回答

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

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

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

var last5 = id.substr(-5);
const r = '6176958e92d42422203a3c58'; 
r.slice(-4)

结果' 3 c58 '

r.slice(-1)

结果“8”

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

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

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

性能

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

结果

适用于所有浏览器

基于切片的解决方案D是最快或最快的 解G最慢

细节

我执行2个测试用例:

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

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

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

这里是chrome的示例结果

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

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


文档:字符串/和