我有

var id="ctl03_Tabs1";

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


当前回答

检查子字符串函数。

要得到最后一个字符:

id.substring(id.length - 1, id.length);

其他回答

获取最后一个字符很容易,因为你可以把字符串当作数组:

var lastChar = id[id.length - 1];

要获取字符串的一部分,可以使用substr函数或substring函数:

id.substr(id.length - 1); //get the last character
id.substr(2);             //get the characters from the 3rd character on
id.substr(2, 1);          //get the 3rd character
id.substr(2, 2);          //get the 3rd and 4th characters

substr和substring之间的区别在于如何处理第二个(可选)参数。在substr中,它是来自索引(第一个参数)的字符量。在substring中,它是字符切片应该结束的位置的索引。

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

如果你只是想要最后一个字符或任何字符在知道的位置,你可以简单地trat字符串作为一个数组!字符串在javascript中是可迭代的

Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d

然而,如果你需要不止一个字符,那么使用拼接是有效的

x.slice(-5);      //world

关于你的例子

"rating_element-<?php echo $id?>"

要提取id,可以很容易地使用split + pop

Id= inputId.split('rating_element-')[1];

返回id,如果'rating_element'后面没有id,则返回undefined :)

下面的脚本显示了使用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()!

使用.slice()方法,因为它是跨浏览器兼容的(见IE问题)。 或者使用.substring()方法。

它们在需求上有一些细微的差异,这些差异被正确地记录在:

const id = "ctl03_Tabs1"; console.log (id.slice (5));/ /输出:Tabs1 console.log (id.slice (1));/ /输出:1 //下面是比较慢的 console.log (id.substring (id。长度- 5));/ /输出:Tabs1 console.log (id.substring (id。长度- 1));/ /输出:1