我有

var id="ctl03_Tabs1";

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


当前回答

const id = "ctl03_Tabs1"; console.log (id.slice (5));/ /输出:Tabs1 console.log (id.slice(0、4));/ /输出:ctl0

其他回答

性能

今天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的示例结果

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

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中,它是字符切片应该结束的位置的索引。

下面的脚本显示了使用JavaScript获取字符串中最后5个字符和最后1个字符的结果:

var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character

输出:

Tabs1 //有5个字符 1 // 1个字符

如果你只是想要最后一个字符或任何字符在知道的位置,你可以简单地trat字符串作为一个数组!字符串在javascript中是可迭代的

Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d

然而,如果你需要不止一个字符,那么使用拼接是有效的

x.slice(-5);      //world

关于你的例子

"rating_element-<?php echo $id?>"

要提取id,可以很容易地使用split + pop

Id= inputId.split('rating_element-')[1];

返回id,如果'rating_element'后面没有id,则返回undefined :)

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

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

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

var last5 = id.substr(-5);