我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
当前回答
假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展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
其他回答
我实际上有以下问题,这是我如何通过上述答案的帮助解决它,但不同的方法提取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
});
const id = "ctl03_Tabs1"; console.log (id.slice (5));/ /输出:Tabs1 console.log (id.slice(0、4));/ /输出:ctl0
这里有两个例子,告诉你总是最后一个字符
var id=“ctl03_Tabs1”; console.log(id.charAt(id.length - 1)); console.log(id[id.length - 1]);
下面的脚本显示了使用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个字符
可以使用起始位置为负的substr()方法来检索最后n个字符。例如,这将得到最后5:
var lastFiveChars = id.substr(-5);