我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
我有
var id="ctl03_Tabs1";
使用JavaScript,如何获得最后五个字符或最后一个字符?
当前回答
你可以用切片
id.slice(-5);
其他回答
我实际上有以下问题,这是我如何通过上述答案的帮助解决它,但不同的方法提取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
});
下面的脚本显示了使用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个字符
你可以利用字符串。长度特性来获取最后一个字符。请看下面的例子:
let str = "hello";
console.log(str[str.length-1]);
// Output : 'o' i.e. Last character.
类似地,您可以使用上面的代码使用for循环来反转字符串。
假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展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
编辑:正如其他人指出的那样,使用slice(-5)而不是substr。但是,请参阅答案底部的.split().pop()解决方案以了解另一种方法。
最初的回答:
你需要使用Javascript字符串方法.substr()结合.length属性。
var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"
这将获取从id开始的字符。长度- 5,由于.substr()的第二个参数被省略,因此将一直持续到字符串的末尾。
您也可以使用.slice()方法,正如其他人在下面指出的那样。
如果你只是想找到下划线后面的字符,你可以使用这个:
var tabId = id.split("_").pop(); // => "Tabs1"
这将字符串拆分为一个下划线数组,然后从数组中“弹出”最后一个元素(这是您想要的字符串)。