我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
当前回答
没有必要使用substr方法来获取字符串的单个字符!
以Jamon Holmgren为例,我们可以改变substr方法,简单地指定数组的位置:
var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"
其他回答
const id = 'ctl03_Tabs1';
id.at(-1); // Returns '1'
At支持负整数从最后一个字符串字符开始计数。
文档:字符串/和
最后 5 个 var id=“ctl03_Tabs1”; var res = id.charAt(id.length-5) 警报;
最后 var id=“ctl03_Tabs1”; var res = id.charAt(id.length-1) 警报;
这里有两个例子,告诉你总是最后一个字符
var id=“ctl03_Tabs1”; console.log(id.charAt(id.length - 1)); console.log(id[id.length - 1]);
检查子字符串函数。
要得到最后一个字符:
id.substring(id.length - 1, id.length);
你可以用切片
id.slice(-5);