我有

var id="ctl03_Tabs1";

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


当前回答

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

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

其他回答

不要使用已弃用的.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

如果逗号是字符串中的最后一个字符,则该命令将删除逗号。

var str = $("#ControlId").val();

if(str.substring(str.length-1)==',') {

  var stringWithoutLastComma = str.substring(0,str.length-1);    

}

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"

如果你只是想要最后一个字符或任何字符在知道的位置,你可以简单地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 :)

检查子字符串函数。

要得到最后一个字符:

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