我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
当前回答
不要使用已弃用的.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
其他回答
没有必要使用substr方法来获取字符串的单个字符!
以Jamon Holmgren为例,我们可以改变substr方法,简单地指定数组的位置:
var id = "ctl03_Tabs1";
var lastChar = id[id.length - 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 :)
检查子字符串函数。
要得到最后一个字符:
id.substring(id.length - 1, id.length);
假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展string类来完成这一点:
String.prototype.endsWith = function (substring) {
if(substring.length > this.length) return false;
return this.substr(this.length - substring.length) === substring;
};
允许您执行以下操作:
var aSentenceToPonder = "This sentence ends with toad";
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true
这里有两个例子,告诉你总是最后一个字符
var id=“ctl03_Tabs1”; console.log(id.charAt(id.length - 1)); console.log(id[id.length - 1]);