如何使用jQuery获取文本字段id中的最后一位数字

时间:2014-08-18 17:21:03

标签: javascript jquery

我必须检索文本字段的ID并找到ID中的最后一个数字。 我这样做了 -

var div_id = parseInt($(row).find('input:text').first().attr('id').length-1);  

但是,这会在ID中提取我的字母数量。 ID的格式为

Ivrgroupzbase_grpzWelcomeNotes
Ivrgroupzbase_grpzWelcomeNotes1
Ivrgroupzbase_grpzWelcomeNotes2
Ivrgroupzbase_grpzWelcomeNotes3

我该怎么做

4 个答案:

答案 0 :(得分:2)

比我的评论更好的解决方案,无论多少都匹配数字:

parseInt(("Ivrgroupzbase_grpzWelcomeNotes".match(/[0-9]+$/) || [0])[0])
0
parseInt(("Ivrgroupzbase_grpzWelcomeNotes123".match(/[0-9]+$/) || [0])[0])
123

答案 1 :(得分:1)

使用正则表达式:

div_id = $(row).find('input:text').first().attr('id').match(/\d+$/)

你在第一个号码中没有得到号码,因为没有号码。

答案 2 :(得分:0)

切片可以很好/轻松。

var $element = $('#Ivrgroupzbase_grpzWelcomeNotes3');

console.log($element.attr('id').slice(-1));

JSFiddle

答案 3 :(得分:0)

您可以使用以下代码:

 var div_id = parseInt($(row).find('input:text').first().attr('id');
 if(div_id.match(/\d+$/)){
     last_number_in_id = div_id.substr(div_id.length-1);
 }else alert (div_id + "has no number");