我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
当前回答
const r = '6176958e92d42422203a3c58';
r.slice(-4)
结果' 3 c58 '
r.slice(-1)
结果“8”
其他回答
一种方法是使用slice,如下所示:
var id="ctl03_Tabs1";
var temp=id.slice(-5);
因此temp的值将是“Tabs1”。
我相信这将工作....
var string1="myfile.pdf"
var esxtenion=string1.substr(string1.length-4)
extension的值是"。pdf"
我实际上有以下问题,这是我如何通过上述答案的帮助解决它,但不同的方法提取id形成一个输入元素。
我已附上输入字段与
id="rating_element-<?php echo $id?>"
并且,当按钮单击时,我想提取的id(这是数字)或php id($id)仅。
这就是我所做的。
$('.rating').on('rating.change', function() {
alert($(this).val());
// console.log(this.id);
var static_id_text=("rating_element-").length;
var product_id = this.id.slice(static_id_text); //get the length in order to deduct from the whole string
console.log(product_id );//outputs the last id appended
});
假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展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";
var res = id.charAt(id.length-1);
我发现了这个问题,通过一些研究,我发现这是得到最后一个字符的最简单的方法。
正如其他人所提到的,为了完整起见,添加了最后5个:
var last5 = id.substr(-5);