最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get numeric part of ID - Stack Overflow

programmeradmin4浏览0评论

If I have the following element:

<div id="ITEM22"></div>

I can get the id like this:

$(this).attr('id');

But how can I get just the numeric part of this if, i.e. 22 ?

EDIT: ITEM is always a prefix.

If I have the following element:

<div id="ITEM22"></div>

I can get the id like this:

$(this).attr('id');

But how can I get just the numeric part of this if, i.e. 22 ?

EDIT: ITEM is always a prefix.

Share Improve this question edited May 9, 2011 at 17:14 santa asked May 9, 2011 at 17:05 santasanta 12.5k51 gold badges160 silver badges265 bronze badges 7
  • 6 Downvote and close? Why? Seems clear enough to me. – spender Commented May 9, 2011 at 17:07
  • 5 Most things are a question of RTM... perhaps SO should be shut down because everything is bleeding obvious? – spender Commented May 9, 2011 at 17:08
  • 2 +1, seems like a legit question. – Abe Miessler Commented May 9, 2011 at 17:09
  • 2 @markus Even though its an easy question, it is still a question about programming. Other beginners searching out there will find the answer useful. – Vincent Ramdhanie Commented May 9, 2011 at 17:10
  • 3 I'm sorry if this seems like an obvious question, but for someone like me with no formal training as a developer, I learn these techniques as they come... – santa Commented May 9, 2011 at 17:11
 |  Show 2 more comments

5 Answers 5

Reset to default 17
var thenumber22 = $(this).attr('id').match(/(\d+)/)[1]

If you always have the prefix ITEM then you can

var numeric = this.id.replace('ITEM','');

and as @Felix mentions in the comments you can convert it directly to a usable number (instead of just a string representation it) by using the + unary operator MDC docs instead

var numeric = +this.id.replace('ITEM','');

Additionally, i have changed the $(this).attr('id') to this.id since this already refers to the object you want and you can directly access its id attribute with this.id

var whatYouWant = getNo($(this).attr('id'));

function getNo(stringNo)
{
    var parsedNo = "";
    for(var n=0; n<stringNo.length; n++)
    {
        var i = stringNo.substring(n,n+1);
        if(i=="1"||i=="2"||i=="3"||i=="4"||i=="5"||i=="6"||i=="7"||i=="8"||i=="9"||i=="0")
            parsedNo += i;
    }
    return parseInt(parsedNo);
}
<div id="ITEM22"></div>

var id = $(this).attr('id');  
var numeric_part = id.replace(/[A-Z]+/, '');  //Output : 22

This extracts digital part of a string using a Regular Expression.

var numericPart = id.match(/\d+/);

发布评论

评论列表(0)

  1. 暂无评论