我有

var id="ctl03_Tabs1";

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


当前回答

要获取字符串的最后一个字符,可以使用split(").pop()函数。

const myText = "The last character is J";
const lastCharater = myText.split('').pop();
console.log(lastCharater); // J

它的工作原理是因为当split(")函数有empty(")作为参数时,字符串的每个字符都被更改为数组的一个元素。因此,我们可以使用pop()函数返回该数组的最后一个元素,即'J'字符。

其他回答

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

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

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

最后 5 个 var id=“ctl03_Tabs1”; var res = id.charAt(id.length-5) 警报;

最后 var id=“ctl03_Tabs1”; var res = id.charAt(id.length-1) 警报;

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

要获取字符串的最后一个字符,可以使用split(").pop()函数。

const myText = "The last character is J";
const lastCharater = myText.split('').pop();
console.log(lastCharater); // J

它的工作原理是因为当split(")函数有empty(")作为参数时,字符串的每个字符都被更改为数组的一个元素。因此,我们可以使用pop()函数返回该数组的最后一个元素,即'J'字符。