我有

var id="ctl03_Tabs1";

使用JavaScript,如何获得最后五个字符或最后一个字符?


当前回答

我实际上有以下问题,这是我如何通过上述答案的帮助解决它,但不同的方法提取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
        });

其他回答

没有必要使用substr方法来获取字符串的单个字符!

以Jamon Holmgren为例,我们可以改变substr方法,简单地指定数组的位置:

var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"

假设你将子字符串与另一个字符串的结尾进行比较,并使用结果作为布尔值,你可以扩展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.substring(id.length - 1, id.length);
const id = 'ctl03_Tabs1';
id.at(-1); // Returns '1'

At支持负整数从最后一个字符串字符开始计数。


文档:字符串/和

这里有两个例子,告诉你总是最后一个字符

var id=“ctl03_Tabs1”; console.log(id.charAt(id.length - 1)); console.log(id[id.length - 1]);