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

How to fetch the last digit in the id of a textfield using jQuery

本文关键字:id 最后一个 数字 字段 取文本 何使用 jQuery 获取      更新时间:2023-09-26

我必须检索文本字段的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

我该怎么做

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

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

使用正则表达式:

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

你不会得到第一个数字,因为没有。

切片会很好/很容易。

var $element = $('#Ivrgroupzbase_grpzWelcomeNotes3');
console.log($element.attr('id').slice(-1));

JSFiddle

您可以使用以下代码:

 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");